from __future__ import annotations

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

from ...core.logger import AppLogger
from ...core.permissions import PERMISSION_COMMISSION_MANAGE, PERMISSION_COMMISSION_VIEW
from ...database.orm import UserORM
from ...services import CommissionService, OperationLogService
from ..dependencies import get_commission_service, get_operation_log_service, require_permission
from ..request_meta import operation_request_meta
from ..schemas.commission import (
    CommissionImportResponse,
    CommissionListResponse,
    CommissionRecordRequest,
    CommissionRecordResponse,
)

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


@router.get("", response_model=CommissionListResponse)
def list_commissions(
    http_request: Request,
    page: int = Query(default=1, ge=1),
    page_size: int = Query(default=10, ge=1, le=100),
    commission_month: str | None = Query(default=None, description="提成月份YYYY-MM"),
    keyword: str | None = Query(default=None, description="员工、类型或业务单号关键字"),
    current_user: UserORM = Depends(require_permission(PERMISSION_COMMISSION_VIEW)),
    service: CommissionService = Depends(get_commission_service),
    operation_logs: OperationLogService = Depends(get_operation_log_service),
) -> CommissionListResponse:
    """分页查询提成记录。"""
    try:
        page_data = service.list_records(
            page=page,
            page_size=page_size,
            commission_month=commission_month,
            keyword=keyword,
        )
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    operation_logs.record(
        actor=current_user,
        module="payroll",
        action="commission.list",
        target_type="commission_record",
        target_id="",
        status="success",
        detail=f"查询提成记录 total={page_data.total} page={page}",
        **operation_request_meta(http_request),
    )
    return CommissionListResponse.from_page(page_data)


@router.post("", response_model=CommissionRecordResponse)
def create_commission(
    http_request: Request,
    request: CommissionRecordRequest,
    current_user: UserORM = Depends(require_permission(PERMISSION_COMMISSION_MANAGE)),
    service: CommissionService = Depends(get_commission_service),
    operation_logs: OperationLogService = Depends(get_operation_log_service),
) -> CommissionRecordResponse:
    """新增提成记录。"""
    try:
        record = service.create_record(**request.model_dump())
    except ValueError as exc:
        operation_logs.record(
            actor=current_user,
            module="payroll",
            action="commission.create",
            target_type="commission_record",
            target_id=str(request.employee_id),
            status="failed",
            detail=str(exc),
            **operation_request_meta(http_request),
        )
        logger.error("新增提成记录失败 employee_id=%s reason=%s", request.employee_id, exc)
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    operation_logs.record(
        actor=current_user,
        module="payroll",
        action="commission.create",
        target_type="commission_record",
        target_id=str(record.id),
        status="success",
        detail=f"新增提成记录 amount={record.amount} month={record.commission_month}",
        **operation_request_meta(http_request),
    )
    return CommissionRecordResponse.from_orm_model(record)


@router.put("/{record_id}", response_model=CommissionRecordResponse)
def update_commission(
    http_request: Request,
    record_id: int,
    request: CommissionRecordRequest,
    current_user: UserORM = Depends(require_permission(PERMISSION_COMMISSION_MANAGE)),
    service: CommissionService = Depends(get_commission_service),
    operation_logs: OperationLogService = Depends(get_operation_log_service),
) -> CommissionRecordResponse:
    """更新提成记录。"""
    try:
        record = service.update_record(record_id, **request.model_dump())
    except ValueError as exc:
        operation_logs.record(
            actor=current_user,
            module="payroll",
            action="commission.update",
            target_type="commission_record",
            target_id=str(record_id),
            status="failed",
            detail=str(exc),
            **operation_request_meta(http_request),
        )
        logger.error("更新提成记录失败 record_id=%s reason=%s", record_id, exc)
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    operation_logs.record(
        actor=current_user,
        module="payroll",
        action="commission.update",
        target_type="commission_record",
        target_id=str(record.id),
        status="success",
        detail=f"更新提成记录 amount={record.amount} month={record.commission_month}",
        **operation_request_meta(http_request),
    )
    return CommissionRecordResponse.from_orm_model(record)


@router.delete("/{record_id}")
def delete_commission(
    http_request: Request,
    record_id: int,
    current_user: UserORM = Depends(require_permission(PERMISSION_COMMISSION_MANAGE)),
    service: CommissionService = Depends(get_commission_service),
    operation_logs: OperationLogService = Depends(get_operation_log_service),
) -> dict[str, str]:
    """删除提成记录。"""
    try:
        service.delete_record(record_id)
    except ValueError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
    operation_logs.record(
        actor=current_user,
        module="payroll",
        action="commission.delete",
        target_type="commission_record",
        target_id=str(record_id),
        status="success",
        detail="删除提成记录成功",
        **operation_request_meta(http_request),
    )
    return {"message": "删除成功"}


@router.post("/import", response_model=CommissionImportResponse)
def import_commissions(
    http_request: Request,
    file: UploadFile = File(...),
    current_user: UserORM = Depends(require_permission(PERMISSION_COMMISSION_MANAGE)),
    service: CommissionService = Depends(get_commission_service),
    operation_logs: OperationLogService = Depends(get_operation_log_service),
) -> CommissionImportResponse:
    """导入提成 Excel。"""
    try:
        count = service.import_excel(file.filename or "commission.xlsx", file.file)
    except ValueError as exc:
        operation_logs.record(
            actor=current_user,
            module="payroll",
            action="commission.import",
            target_type="file",
            target_id=file.filename or "",
            status="failed",
            detail=str(exc),
            **operation_request_meta(http_request),
        )
        logger.error("导入提成Excel失败 filename=%s reason=%s", file.filename, exc)
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    operation_logs.record(
        actor=current_user,
        module="payroll",
        action="commission.import",
        target_type="file",
        target_id=file.filename or "",
        status="success",
        detail=f"导入提成Excel成功 count={count}",
        **operation_request_meta(http_request),
    )
    return CommissionImportResponse(imported_count=count, message="导入成功")
