"""代理卡密：列表、代理备注。"""

from typing import Literal

from fastapi import APIRouter, Query

from app.dependencies import AgentUser, DbSession
from app.schemas.admin_card_key import CardKeyOut
from app.schemas.agent_card_key import AgentCardKeyUpdate
from app.schemas.common import ApiResponse, PaginatedData
from app.services import agent_card_key as card_key_service

router = APIRouter(prefix="/agent/card-keys", tags=["代理-卡密"])


@router.get("", response_model=ApiResponse[PaginatedData[CardKeyOut]])
async def list_card_keys(
    agent: AgentUser,
    db: DbSession,
    page: int = Query(1, ge=1),
    page_size: int = Query(
        card_key_service.DEFAULT_PAGE_SIZE,
        ge=1,
        le=card_key_service.MAX_PAGE_SIZE,
    ),
    status: Literal["all", "unused", "used"] | None = Query(
        default="all",
        description="筛选：all 全部 / unused 未使用 / used 已激活",
    ),
    username: str | None = Query(default=None, description="按激活用户名模糊筛选"),
) -> ApiResponse[PaginatedData[CardKeyOut]]:
    filter_status = None if status == "all" else status
    cards, total = await card_key_service.list_card_keys(
        db,
        agent_id=agent.id,
        page=page,
        page_size=page_size,
        status=filter_status,
        username=username,
    )
    return ApiResponse(
        ok=True,
        message="",
        data=PaginatedData.build(
            [CardKeyOut.model_validate(c) for c in cards],
            total=total,
            page=page,
            page_size=page_size,
        ),
    )


@router.patch("/{card_id}", response_model=ApiResponse[CardKeyOut])
async def update_card_key(
    card_id: int,
    body: AgentCardKeyUpdate,
    agent: AgentUser,
    db: DbSession,
) -> ApiResponse[CardKeyOut]:
    try:
        card = await card_key_service.update_card_key(
            db, card_id, body, agent_id=agent.id
        )
    except card_key_service.AgentCardKeyError as exc:
        return ApiResponse(ok=False, message=exc.message)

    return ApiResponse(
        ok=True,
        message="备注已更新",
        data=CardKeyOut.model_validate(card),
    )
