from __future__ import annotations

from typing import Annotated

from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status

from app.api.deps import CurrentUserContext, get_current_user
from app.db.session import get_session_factory
from app.schemas.common import ErrorResponse
from app.schemas.linked_reimbursement_draft_job import (
    LinkedReimbursementDraftJobCreate,
    LinkedReimbursementDraftJobRead,
)
from app.services.linked_reimbursement_draft_jobs import (
    create_linked_reimbursement_draft_job,
    get_linked_reimbursement_draft_job,
    run_linked_reimbursement_draft_job,
)

router = APIRouter(prefix="/reimbursements/linked-reimbursement-draft-jobs")
CurrentUser = Annotated[CurrentUserContext, Depends(get_current_user)]


@router.post(
    "",
    response_model=LinkedReimbursementDraftJobRead,
    status_code=status.HTTP_202_ACCEPTED,
    summary="创建关联申请单生成报销草稿后台任务",
    description="用户选择关联申请单后，后台继续生成报销草稿，避免当前会话长时间同步等待。",
    responses={
        status.HTTP_400_BAD_REQUEST: {
            "model": ErrorResponse,
            "description": "请求缺少申请单关联上下文。",
        },
    },
)
def create_linked_reimbursement_draft_job_endpoint(
    payload: LinkedReimbursementDraftJobCreate,
    background_tasks: BackgroundTasks,
    current_user: CurrentUser,
) -> LinkedReimbursementDraftJobRead:
    try:
        job = create_linked_reimbursement_draft_job(payload, current_user)
    except ValueError as exc:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
    background_tasks.add_task(
        run_linked_reimbursement_draft_job,
        job.job_id,
        current_user,
        get_session_factory(),
    )
    return job


@router.get(
    "/{job_id}",
    response_model=LinkedReimbursementDraftJobRead,
    summary="查询关联申请单生成报销草稿后台任务",
    description="用于前端按 job_id 查询草稿生成状态。",
    responses={
        status.HTTP_404_NOT_FOUND: {
            "model": ErrorResponse,
            "description": "任务不存在或当前用户无权查看。",
        },
    },
)
def get_linked_reimbursement_draft_job_endpoint(
    job_id: str,
    current_user: CurrentUser,
) -> LinkedReimbursementDraftJobRead:
    job = get_linked_reimbursement_draft_job(job_id, current_user)
    if job is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销草稿生成任务不存在或已失效。")
    return job
