from __future__ import annotations

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

from ...core.logger import AppLogger
from ...core.permissions import PERMISSION_SALARY_PROFILE_MANAGE, PERMISSION_SALARY_PROFILE_VIEW
from ...database.orm import UserORM
from ...services import OperationLogService, SalaryProfileService
from ..dependencies import get_operation_log_service, get_salary_profile_service, require_permission
from ..request_meta import operation_request_meta
from ..schemas.salary_profile import SalaryProfileRequest, SalaryProfileResponse

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


@router.get("", response_model=list[SalaryProfileResponse])
def list_salary_profiles(
    http_request: Request,
    keyword: str | None = Query(default=None, description="员工编号、姓名、部门或岗位关键字"),
    current_user: UserORM = Depends(require_permission(PERMISSION_SALARY_PROFILE_VIEW)),
    service: SalaryProfileService = Depends(get_salary_profile_service),
    operation_logs: OperationLogService = Depends(get_operation_log_service),
) -> list[SalaryProfileResponse]:
    """查询薪资档案。"""
    profiles = service.list_profiles(keyword=keyword)
    operation_logs.record(
        actor=current_user,
        module="payroll",
        action="salary_profile.list",
        target_type="salary_profile",
        target_id="",
        status="success",
        detail=f"查询薪资档案 count={len(profiles)}",
        **operation_request_meta(http_request),
    )
    return [SalaryProfileResponse.from_orm_model(profile) for profile in profiles]


@router.put("/{employee_id}", response_model=SalaryProfileResponse)
def upsert_salary_profile(
    http_request: Request,
    employee_id: int,
    request: SalaryProfileRequest,
    current_user: UserORM = Depends(require_permission(PERMISSION_SALARY_PROFILE_MANAGE)),
    service: SalaryProfileService = Depends(get_salary_profile_service),
    operation_logs: OperationLogService = Depends(get_operation_log_service),
) -> SalaryProfileResponse:
    """按员工维护当前薪资档案，包含底薪、提成和独立加班费单价。"""
    if request.employee_id != employee_id:
        raise HTTPException(status_code=400, detail="路径员工ID与请求员工ID不一致")
    try:
        profile = service.upsert_profile(**request.model_dump())
    except ValueError as exc:
        operation_logs.record(
            actor=current_user,
            module="payroll",
            action="salary_profile.upsert",
            target_type="employee",
            target_id=str(employee_id),
            status="failed",
            detail=str(exc),
            **operation_request_meta(http_request),
        )
        logger.error("保存薪资档案失败 employee_id=%s reason=%s", employee_id, exc)
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    operation_logs.record(
        actor=current_user,
        module="payroll",
        action="salary_profile.upsert",
        target_type="employee",
        target_id=str(employee_id),
        status="success",
        detail=(
            f"保存薪资档案成功 base_salary={profile.base_salary} "
            f"commission={profile.commission_amount} overtime_rate={profile.overtime_rate}"
        ),
        **operation_request_meta(http_request),
    )
    return SalaryProfileResponse.from_orm_model(profile)
