# -*- coding: utf-8 -*-
"""
小程序任务路由 —— 任务列表、任务详情、置顶、放弃、取消放弃。

端点清单：
- GET  /api/xcx/tasks                  — 获取任务列表 + 绩效概览（TASK-1）
- GET  /api/xcx/tasks/{task_id}        — 获取任务详情完整版（TASK-2）
- POST /api/xcx/tasks/{id}/pin         — 置顶任务
- POST /api/xcx/tasks/{id}/unpin       — 取消置顶
- POST /api/xcx/tasks/{id}/abandon     — 放弃任务
- POST /api/xcx/tasks/{id}/restore     — 恢复任务

所有端点均需 JWT（approved 状态）。
"""

from __future__ import annotations

from fastapi import APIRouter, Depends, Query

from app.auth.dependencies import CurrentUser
from app.middleware.permission import require_approved
from app.schemas.xcx_tasks import (
    AbandonRequest,
    TaskDetailResponse,
    TaskListResponse,
)
from app.services import task_manager

router = APIRouter(prefix="/api/xcx/tasks", tags=["小程序任务"])


@router.get("", response_model=TaskListResponse)
async def get_tasks(
    status: str = Query("pending", pattern="^(pending|completed|abandoned)$"),
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=100),
    user: CurrentUser = Depends(require_approved()),
):
    """获取任务列表 + 绩效概览。"""
    return await task_manager.get_task_list_v2(
        user.user_id, user.site_id, status, page, page_size
    )


@router.get("/{task_id}", response_model=TaskDetailResponse)
async def get_task_detail(
    task_id: int,
    user: CurrentUser = Depends(require_approved()),
):
    """获取任务详情完整版。"""
    return await task_manager.get_task_detail(
        task_id, user.user_id, user.site_id
    )


@router.post("/{task_id}/pin")
async def pin_task(
    task_id: int,
    user: CurrentUser = Depends(require_approved()),
):
    """置顶任务。"""
    result = await task_manager.pin_task(task_id, user.user_id, user.site_id)
    return {"is_pinned": result["is_pinned"]}


@router.post("/{task_id}/unpin")
async def unpin_task(
    task_id: int,
    user: CurrentUser = Depends(require_approved()),
):
    """取消置顶。"""
    result = await task_manager.unpin_task(task_id, user.user_id, user.site_id)
    return {"is_pinned": result["is_pinned"]}


@router.post("/{task_id}/abandon")
async def abandon_task(
    task_id: int,
    body: AbandonRequest,
    user: CurrentUser = Depends(require_approved()),
):
    """放弃任务（需填写原因）。"""
    return await task_manager.abandon_task(
        task_id, user.user_id, user.site_id, body.reason
    )


@router.post("/{task_id}/restore")
async def restore_task(
    task_id: int,
    user: CurrentUser = Depends(require_approved()),
):
    """取消放弃，恢复为活跃状态。"""
    return await task_manager.cancel_abandon(task_id, user.user_id, user.site_id)
