"""Entry association helpers — shared across blog and events apps.

Only uses HTTP-based fetch_data/call_action, no direct DB access.
"""
from __future__ import annotations

from shared.infrastructure.actions import call_action, ActionError
from shared.infrastructure.data_client import fetch_data
from shared.contracts.dtos import CalendarEntryDTO, dto_from_dict


async def toggle_entry_association(
    post_id: int,
    entry_id: int
) -> tuple[bool, str | None]:
    """
    Toggle association between a post and calendar entry.
    Returns (is_now_associated, error_message).
    """
    post = await fetch_data("blog", "post-by-id", params={"id": post_id}, required=False)
    if not post:
        return False, "Post not found"

    try:
        result = await call_action("events", "toggle-entry-post", payload={
            "entry_id": entry_id, "content_type": "post", "content_id": post_id,
        })
        return result.get("is_associated", False), None
    except ActionError as e:
        return False, str(e)


async def get_post_entry_ids(
    post_id: int
) -> set[int]:
    """
    Get all entry IDs associated with this post.
    Returns a set of entry IDs.
    """
    raw = await fetch_data("events", "entry-ids-for-content",
                           params={"content_type": "post", "content_id": post_id},
                           required=False) or []
    return set(raw)


async def get_associated_entries(
    post_id: int,
    page: int = 1,
    per_page: int = 10
) -> dict:
    """
    Get paginated associated entries for this post.
    Returns dict with entries (CalendarEntryDTOs), total_count, and has_more.
    """
    raw = await fetch_data("events", "associated-entries",
                           params={"content_type": "post", "content_id": post_id, "page": page},
                           required=False) or {"entries": [], "has_more": False}
    entries = [dto_from_dict(CalendarEntryDTO, e) for e in raw.get("entries", [])]
    has_more = raw.get("has_more", False)
    total_count = len(entries) + (page - 1) * per_page
    if has_more:
        total_count += 1

    return {
        "entries": entries,
        "total_count": total_count,
        "has_more": has_more,
        "page": page,
    }
