"""Administrative endpoints for billing records."""

from __future__ import annotations

from aiohttp import web

from ..app_keys import BILLING_STORE_KEY, REQUIRE_ADMIN_KEY
from ..jobs.reconcile_billing import reconcile_pending as reconcile_job
from ..stores import BillingStore


async def list_billing_records(request: web.Request) -> web.Response:
    _require_admin(request)
    org_id = request.match_info.get("org_id")
    if not org_id:
        raise web.HTTPBadRequest(text="org_id missing")

    limit = int(request.query.get("limit", 50))
    limit = max(1, min(limit, 500))
    cursor = request.query.get("cursor")

    store = _billing_store(request)
    try:
        records = store.list_records(org_id, limit=limit, cursor=cursor)
    except ValueError as exc:
        raise web.HTTPBadRequest(text=str(exc)) from exc
    return web.json_response(records)


async def reconcile_pending(request: web.Request) -> web.Response:
    _require_admin(request)
    store = _billing_store(request)
    count = reconcile_job(store)
    return web.json_response({"ok": True, "reconciled": count})


def register(app: web.Application) -> None:
    app.router.add_get("/v1/admin/billing/{org_id}", list_billing_records)
    app.router.add_post("/v1/admin/billing/reconcile", reconcile_pending)


def _billing_store(request: web.Request) -> BillingStore:
    store = request.app.get(BILLING_STORE_KEY)
    if store is None:
        raise web.HTTPServiceUnavailable(text="billing store unavailable")
    return store


def _require_admin(request: web.Request) -> None:
    checker = request.app.get(REQUIRE_ADMIN_KEY)
    if callable(checker):
        checker(request)
    else:
        raise web.HTTPForbidden(text="Admin guard not configured")
