"""一次性任务 endpoint。

路由前缀 `/api/v1/tasks`:
  GET  /                    任务及领取状态(如"打开消息提醒")
  POST /{task_key}/claim    领取任务奖励
"""
from __future__ import annotations

import logging

from fastapi import APIRouter, HTTPException, status

from app.api.deps import CurrentUser, DbSession
from app.repositories import risk as risk_repo
from app.repositories import task as crud_task
from app.schemas.welfare import TaskClaimResultOut, TaskListOut, TaskOut

logger = logging.getLogger("shagua.tasks")

router = APIRouter(prefix="/api/v1/tasks", tags=["tasks"])


@router.get("", response_model=TaskListOut, summary="任务及领取状态")
def list_tasks(user: CurrentUser, db: DbSession) -> TaskListOut:
    states = crud_task.list_tasks(db, user.id)
    return TaskListOut(
        items=[
            TaskOut(task_key=s.task_key, coin=s.coin, claimed=s.claimed)
            for s in states
        ]
    )


@router.post(
    "/{task_key}/claim",
    response_model=TaskClaimResultOut,
    summary="领取任务奖励",
)
def claim_task(task_key: str, user: CurrentUser, db: DbSession) -> TaskClaimResultOut:
    if risk_repo.is_restricted(
        db,
        subject_type="user",
        subject_id=str(user.id),
        scope=risk_repo.SCOPE_ECONOMIC_ACCOUNT,
    ):
        raise HTTPException(status_code=403, detail="账号存在异常，该功能暂不可用")
    try:
        coin, balance = crud_task.claim_task(db, user.id, task_key)
    except crud_task.UnknownTaskError as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="unknown task") from e
    except crud_task.AlreadyClaimedError as e:
        raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="task already claimed") from e

    logger.info("task claimed user_id=%d key=%s coin=%d", user.id, task_key, coin)
    return TaskClaimResultOut(task_key=task_key, coin_awarded=coin, coin_balance=balance)
