"""管理员卡密 CRUD。"""

from typing import Literal

from fastapi import APIRouter, Query

from app.dependencies import AdminUser, DbSession
from app.schemas.admin_card_key import (
    CardKeyBatchCreateResult,
    CardKeyCreate,
    CardKeyOut,
    CardKeyUpdate,
)
from app.schemas.common import ApiResponse, PaginatedData
from app.services import admin_card_key as card_key_service

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


@router.get("", response_model=ApiResponse[PaginatedData[CardKeyOut]])
async def list_card_keys(
    _admin: AdminUser,
    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="按激活用户名模糊筛选"),
    oem_id: int | None = Query(default=None, description="按预分配 OEM 筛选"),
    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,
        page=page,
        page_size=page_size,
        status=filter_status,
        username=username,
        oem_id=oem_id,
        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.post("", response_model=ApiResponse[CardKeyBatchCreateResult])
async def create_card_keys(
    body: CardKeyCreate,
    _admin: AdminUser,
    db: DbSession,
) -> ApiResponse[CardKeyBatchCreateResult]:
    try:
        created = await card_key_service.create_card_keys(db, body)
    except card_key_service.AdminCardKeyError as exc:
        return ApiResponse(ok=False, message=exc.message)

    items = [CardKeyOut.model_validate(c) for c in created]
    return ApiResponse(
        ok=True,
        message=f"已生成 {len(items)} 张卡密",
        data=CardKeyBatchCreateResult(items=items, created_count=len(items)),
    )


@router.patch("/{card_id}", response_model=ApiResponse[CardKeyOut])
async def update_card_key(
    card_id: int,
    body: CardKeyUpdate,
    _admin: AdminUser,
    db: DbSession,
) -> ApiResponse[CardKeyOut]:
    try:
        card = await card_key_service.update_card_key(db, card_id, body)
    except card_key_service.AdminCardKeyError as exc:
        return ApiResponse(ok=False, message=exc.message)

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


@router.delete("/{card_id}", response_model=ApiResponse[None])
async def delete_card_key(
    card_id: int,
    _admin: AdminUser,
    db: DbSession,
) -> ApiResponse[None]:
    try:
        await card_key_service.delete_card_key(db, card_id)
    except card_key_service.AdminCardKeyError as exc:
        return ApiResponse(ok=False, message=exc.message)

    return ApiResponse(ok=True, message="卡密已删除")
