"""用户卡密激活。"""

from fastapi import APIRouter

from app.dependencies import DbSession
from app.schemas.card_key import CardKeyActivateRequest, CardKeyActivateResponse
from app.schemas.common import ApiResponse
from app.services import card_key_activate as activate_service

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


@router.post("/activate", response_model=ApiResponse[CardKeyActivateResponse])
async def activate_card_key(
    body: CardKeyActivateRequest,
    db: DbSession,
) -> ApiResponse[CardKeyActivateResponse]:
    try:
        data = await activate_service.activate_card_key(
            db,
            username=body.username,
            serial_number=body.serial_number,
        )
    except activate_service.CardKeyActivateError as exc:
        return ApiResponse(ok=False, message=exc.message)

    if data.card_type == "时长":
        message = f"激活成功，会员已延长 {data.added_days} 天"
    else:
        message = f"激活成功，已获得 {data.added_points} 点数"

    return ApiResponse(ok=True, message=message, data=data)
