from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException, Query, Request

from ...core.logger import AppLogger
from ...core.permissions import PERMISSION_REPORT_VIEW
from ...database.orm import UserORM
from ...services import OperationLogService, ReportService
from ..dependencies import get_operation_log_service, get_report_service, require_permission
from ..request_meta import operation_request_meta
from ..schemas.report import PayrollReportResponse

router = APIRouter(prefix="/api/reports", tags=["reports"])
logger = AppLogger.get_logger(__name__)


@router.get("/payroll-summary", response_model=PayrollReportResponse)
def payroll_summary(
    http_request: Request,
    salary_month: str | None = Query(default=None, description="工资月份YYYY-MM"),
    current_user: UserORM = Depends(require_permission(PERMISSION_REPORT_VIEW)),
    service: ReportService = Depends(get_report_service),
    operation_logs: OperationLogService = Depends(get_operation_log_service),
) -> PayrollReportResponse:
    """查询薪资、考勤和部门维度的统计报表。"""
    try:
        report = service.payroll_summary(salary_month=salary_month)
    except ValueError as exc:
        logger.error("查询统计报表失败 salary_month=%s reason=%s", salary_month, exc)
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    operation_logs.record(
        actor=current_user,
        module="report",
        action="report.payroll_summary",
        target_type="salary_record",
        target_id=salary_month or "",
        status="success",
        detail=f"查询工资统计报表 employee_count={report.totals['employee_count']}",
        **operation_request_meta(http_request),
    )
    return PayrollReportResponse.from_report(report)
