"""Mailio backend API integration for storing and querying receipts."""

from __future__ import annotations

from dataclasses import dataclass

import httpx

from mailio_receipt.models import MailioReceipt


@dataclass(frozen=True)
class ReceiptsResponse:
    """Response containing multiple receipts."""

    receipts: tuple[MailioReceipt, ...]


async def save_receipt(
    receipt: MailioReceipt,
    *,
    base_url: str,
    api_key: str,
) -> MailioReceipt:
    """
    Save a receipt to the Mailio backend.

    POST /api/v1/receipts

    Args:
        receipt: The receipt to save.
        base_url: Backend base URL (e.g. "https://mio.mailiomail.com").
        api_key: API key for authentication.

    Returns:
        The saved MailioReceipt as returned by the server.

    Raises:
        httpx.HTTPStatusError: If the server returns an error status.
    """
    url = f"{base_url.rstrip('/')}/api/v1/receipts"
    async with httpx.AsyncClient() as client:
        resp = await client.post(
            url,
            json=receipt.to_dict(),
            headers={"X-API-Key": api_key},
        )
        resp.raise_for_status()
        return MailioReceipt.from_dict(resp.json())


async def get_receipt(
    receipt_id: str,
    *,
    base_url: str,
    api_key: str,
) -> MailioReceipt:
    """
    Fetch a single receipt by ID.

    GET /api/v1/receipts/{id}

    Args:
        receipt_id: The receipt ID to fetch.
        base_url: Backend base URL (e.g. "https://mio.mailiomail.com").
        api_key: API key for authentication.

    Returns:
        The MailioReceipt.

    Raises:
        httpx.HTTPStatusError: If the server returns an error status.
    """
    url = f"{base_url.rstrip('/')}/api/v1/receipts/{receipt_id}"
    async with httpx.AsyncClient() as client:
        resp = await client.get(
            url,
            headers={"X-API-Key": api_key},
        )
        resp.raise_for_status()
        return MailioReceipt.from_dict(resp.json())


async def get_receipts_by_flow(
    flow_id: str,
    *,
    base_url: str,
    api_key: str,
) -> ReceiptsResponse:
    """
    Fetch all receipts belonging to a flow.

    GET /api/v1/receipts/flow/{flow_id}

    Args:
        flow_id: The flow ID to query.
        base_url: Backend base URL (e.g. "https://mio.mailiomail.com").
        api_key: API key for authentication.

    Returns:
        ReceiptsResponse containing the list of receipts.

    Raises:
        httpx.HTTPStatusError: If the server returns an error status.
    """
    url = f"{base_url.rstrip('/')}/api/v1/receipts/flow/{flow_id}"
    async with httpx.AsyncClient() as client:
        resp = await client.get(
            url,
            headers={"X-API-Key": api_key},
        )
        resp.raise_for_status()
        data = resp.json()
        receipts = tuple(
            MailioReceipt.from_dict(r) for r in data.get("receipts", [])
        )
        return ReceiptsResponse(receipts=receipts)
