"""Payment monitoring tools."""

from __future__ import annotations

from typing import Any

from mcp.types import ToolAnnotations

from mcp_eregistrations_ds.ds_client import DSClient, DSClientError, translate_error
from mcp_eregistrations_ds.server import mcp


def _summarize_provider(item: dict[str, Any]) -> dict[str, Any]:
    """Build a summary dict for a payment provider."""
    return {
        "code": item.get("code"),
        "name": item.get("name"),
    }


def _summarize_transaction(item: dict[str, Any]) -> dict[str, Any]:
    """Build a summary dict for a payment transaction list item."""
    provider = item.get("payment_provider")
    return {
        "transaction_id": item.get("transaction_id"),
        "status": item.get("status"),
        "total_cost": item.get("total_cost"),
        "cost_currency": item.get("cost_currency"),
        "provider": provider.get("code") if isinstance(provider, dict) else provider,
        "file_id": item.get("file_id"),
        "service_name": item.get("service_name"),
        "created_at": item.get("created_at"),
    }


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
async def payment_provider_list(
    instance: str | None = None,
) -> dict[str, Any]:
    """List configured payment providers.

    Args:
        instance: Instance profile name.

    Returns:
        dict with total, providers (code, name).
    """
    try:
        async with DSClient.for_instance(instance) as client:
            data = await client.get("/backend/payment_providers")
    except DSClientError as e:
        raise translate_error(e, resource_type="payment_provider") from e

    providers = data if isinstance(data, list) else data.get("results", [])
    return {
        "total": len(providers),
        "providers": [_summarize_provider(p) for p in providers],
    }


@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
async def payment_transaction_list(
    file_id: str | None = None,
    page: int = 1,
    instance: str | None = None,
) -> dict[str, Any]:
    """List payment transactions.

    Args:
        file_id: Filter by file UUID.
        page: Page number (default: 1).
        instance: Instance profile name.

    Returns:
        dict with items (summary fields only), count, page, page_size, has_next.
    """
    params: dict[str, Any] = {"page": page}
    if file_id:
        params["file_id"] = file_id

    try:
        async with DSClient.for_instance(instance) as client:
            data = await client.get_paginated(
                "/backend/payment_transaction", params=params
            )
    except DSClientError as e:
        raise translate_error(e, resource_type="payment_transaction") from e

    data["items"] = [_summarize_transaction(item) for item in data.get("items", [])]
    return data
