from __future__ import annotations

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

from ...core.logger import AppLogger
from ...core.permissions import PERMISSION_CONFIG_MANAGE, PERMISSION_CONFIG_VIEW
from ...database.orm import UserORM
from ...services import OperationLogService, SalaryConfigService
from ..dependencies import get_operation_log_service, get_salary_config_service, require_permission
from ..request_meta import operation_request_meta
from ..schemas.salary_config import (
    SalaryConfigDefaultsResponse,
    SalaryConfigRequest,
    SalaryConfigResponse,
)

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


@router.get("", response_model=list[SalaryConfigResponse])
def list_configs(
    http_request: Request,
    config_group: str | None = Query(default=None, description="配置分组：attendance、payroll等"),
    current_user: UserORM = Depends(require_permission(PERMISSION_CONFIG_VIEW)),
    service: SalaryConfigService = Depends(get_salary_config_service),
    operation_logs: OperationLogService = Depends(get_operation_log_service),
) -> list[SalaryConfigResponse]:
    """查询系统规则配置。"""
    configs = service.list_configs(config_group=config_group)
    operation_logs.record(
        actor=current_user,
        module="system",
        action="config.list",
        target_type="salary_config",
        target_id=config_group or "",
        status="success",
        detail=f"查询系统配置 count={len(configs)}",
        **operation_request_meta(http_request),
    )
    return [SalaryConfigResponse.from_orm_model(config) for config in configs]


@router.put("/{config_key:path}", response_model=SalaryConfigResponse)
def update_config(
    http_request: Request,
    config_key: str,
    request: SalaryConfigRequest,
    current_user: UserORM = Depends(require_permission(PERMISSION_CONFIG_MANAGE)),
    service: SalaryConfigService = Depends(get_salary_config_service),
    operation_logs: OperationLogService = Depends(get_operation_log_service),
) -> SalaryConfigResponse:
    """更新单个规则配置。"""
    try:
        config = service.update_config(config_key, request.to_update())
    except (ValueError, TypeError) as exc:
        operation_logs.record(
            actor=current_user,
            module="system",
            action="config.update",
            target_type="salary_config",
            target_id=config_key,
            status="failed",
            detail=str(exc),
            **operation_request_meta(http_request),
        )
        logger.error("更新系统配置失败 config_key=%s reason=%s", config_key, exc)
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    operation_logs.record(
        actor=current_user,
        module="system",
        action="config.update",
        target_type="salary_config",
        target_id=config_key,
        status="success",
        detail="更新系统配置成功",
        **operation_request_meta(http_request),
    )
    return SalaryConfigResponse.from_orm_model(config)


@router.post("/defaults", response_model=SalaryConfigDefaultsResponse)
def ensure_default_configs(
    http_request: Request,
    current_user: UserORM = Depends(require_permission(PERMISSION_CONFIG_MANAGE)),
    service: SalaryConfigService = Depends(get_salary_config_service),
    operation_logs: OperationLogService = Depends(get_operation_log_service),
) -> SalaryConfigDefaultsResponse:
    """补齐系统默认规则配置。"""
    count = service.ensure_defaults()
    operation_logs.record(
        actor=current_user,
        module="system",
        action="config.defaults",
        target_type="salary_config",
        target_id="defaults",
        status="success",
        detail=f"补齐默认配置 created={count}",
        **operation_request_meta(http_request),
    )
    return SalaryConfigDefaultsResponse(created_count=count, message="默认配置已检查")
