from __future__ import annotations

from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from app.api.deps import CurrentUserContext, get_current_user, get_db
from app.schemas.expense_case import ExpenseCaseTimelineRead
from app.services.expense_cases import ExpenseCaseService
from app.services.expense_claims import ExpenseClaimService

router = APIRouter(prefix="/expense-cases")
DbSession = Annotated[Session, Depends(get_db)]
CurrentUser = Annotated[CurrentUserContext, Depends(get_current_user)]


@router.get(
    "/by-claim/{claim_id}",
    response_model=ExpenseCaseTimelineRead,
    summary="查询报销单所属费用事件时间线",
    description="返回当前用户有权查看的费用事件、关联单据和结构化业务事件。",
)
def get_expense_case_by_claim(
    claim_id: str,
    db: DbSession,
    current_user: CurrentUser,
) -> ExpenseCaseTimelineRead:
    claim = ExpenseClaimService(db).get_claim(claim_id, current_user)
    if claim is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="费用单据不存在。")

    expense_case = ExpenseCaseService(db).get_timeline_for_claim(
        claim.id,
        tenant_id=current_user.tenant_id,
    )
    if expense_case is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="该单据尚未纳入统一费用事件。",
        )
    return ExpenseCaseTimelineRead.model_validate(expense_case)
