from __future__ import annotations

from datetime import datetime

from fastapi import APIRouter, Depends, Query, Request

from ...core.logger import AppLogger
from ...core.permissions import PERMISSION_OPERATION_LOG_VIEW
from ...database.orm import UserORM
from ...services import OperationLogService
from ..dependencies import get_operation_log_service, require_permission
from ..request_meta import operation_request_meta
from ..schemas.operation_log import OperationLogListResponse

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


@router.get("", response_model=OperationLogListResponse)
def list_operation_logs(
    http_request: Request,
    page: int = Query(default=1, ge=1, description="页码，从1开始"),
    page_size: int = Query(default=20, ge=1, le=100, description="每页条数，最大100"),
    username: str | None = Query(default=None, description="按用户名模糊筛选"),
    module: str | None = Query(default=None, description="按模块精确筛选"),
    action: str | None = Query(default=None, description="按动作精确筛选"),
    status: str | None = Query(default=None, description="按状态筛选：success或failed"),
    keyword: str | None = Query(default=None, description="关键字模糊筛选"),
    start_time: datetime | None = Query(default=None, description="开始时间"),
    end_time: datetime | None = Query(default=None, description="结束时间"),
    current_user: UserORM = Depends(require_permission(PERMISSION_OPERATION_LOG_VIEW)),
    service: OperationLogService = Depends(get_operation_log_service),
) -> OperationLogListResponse:
    """查看操作日志，支持分页和常用筛选。"""
    page_data = service.list_logs(
        page=page,
        page_size=page_size,
        username=username,
        module=module,
        action=action,
        status=status,
        keyword=keyword,
        start_time=start_time,
        end_time=end_time,
    )
    service.record(
        actor=current_user,
        module="system",
        action="operation_log.view",
        target_type="operation_log",
        target_id="",
        status="success",
        detail=f"查看操作日志 page={page_data.page} page_size={page_data.page_size} total={page_data.total}",
        **operation_request_meta(http_request),
    )
    logger.info("操作日志接口查询成功 user_id=%s total=%s", current_user.id, page_data.total)
    return OperationLogListResponse.from_page(page_data)
