from typing import List

from fastapi import APIRouter, Depends, HTTPException, status

from app.api.deps import RequestContext, get_request_context
from app.models.credits import CreditLogItem, CreditSummary
from app.services import credits

router = APIRouter()


@router.get("", response_model=CreditSummary)
async def get_credit_summary(
    ctx: RequestContext = Depends(get_request_context),
) -> CreditSummary:
    try:
        summary = credits.get_credit_summary(ctx.user_id)
        return CreditSummary(**summary)
    except Exception as exc:  # pragma: no cover - unexpected
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(exc),
        ) from exc


@router.get("/logs", response_model=List[CreditLogItem])
async def get_credit_logs(
    limit: int = 50,
    ctx: RequestContext = Depends(get_request_context),
) -> List[CreditLogItem]:
    try:
        logs = credits.get_credit_logs(ctx.user_id, limit=limit)
        return [CreditLogItem(**item) for item in logs]
    except Exception as exc:  # pragma: no cover - unexpected
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(exc),
        ) from exc
