"""OEM 卡密：列表、备注、批量分配给代理。"""

from typing import Literal

from fastapi import APIRouter, Query

from app.dependencies import DbSession, OemUser
from app.schemas.admin_card_key import CardKeyOut
from app.schemas.common import ApiResponse, PaginatedData
from app.schemas.oem_card_key import (
    OemCardKeyBatchAssign,
    OemCardKeyBatchAssignResult,
    OemCardKeyUpdate,
)
from app.services import oem_card_key as card_key_service

router = APIRouter(prefix="/oem/card-keys", tags=["OEM-卡密"])


@router.get("", response_model=ApiResponse[PaginatedData[CardKeyOut]])
async def list_card_keys(
    oem: OemUser,
    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="按激活用户名模糊筛选"),
    agent_id: int | 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,
        oem_id=oem.id,
        page=page,
        page_size=page_size,
        status=filter_status,
        username=username,
        agent_id=agent_id,
    )
    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: OemCardKeyUpdate,
    oem: OemUser,
    db: DbSession,
) -> ApiResponse[CardKeyOut]:
    try:
        card = await card_key_service.update_card_key(
            db, card_id, body, oem_id=oem.id
        )
    except card_key_service.OemCardKeyError as exc:
        return ApiResponse(ok=False, message=exc.message)

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


@router.post("/assign-agent", response_model=ApiResponse[OemCardKeyBatchAssignResult])
async def batch_assign_to_agent(
    body: OemCardKeyBatchAssign,
    oem: OemUser,
    db: DbSession,
) -> ApiResponse[OemCardKeyBatchAssignResult]:
    try:
        count = await card_key_service.batch_assign_to_agent(
            db, body, oem_id=oem.id
        )
    except card_key_service.OemCardKeyError as exc:
        return ApiResponse(ok=False, message=exc.message)

    return ApiResponse(
        ok=True,
        message=f"已分配 {count} 张卡密",
        data=OemCardKeyBatchAssignResult(updated_count=count),
    )
