"""
审计日志 API 接口

仅管理员可访问
"""
from typing import List, Optional
from uuid import UUID
from datetime import datetime
from fastapi import APIRouter, Depends, Query, Path
from app.domain.schemas.audit import AuditLogResponse
from app.infra.repositories.audit_repository import AuditRepository
from app.auth.metadata_dependencies import (
    get_current_metadata_admin,
    get_current_metadata_user,
)
from app.infra.db.metadb.database import get_metadata_session
from sqlalchemy.ext.asyncio import AsyncSession

router = APIRouter()

async def get_audit_repository(
    session: AsyncSession = Depends(get_metadata_session),
) -> AuditRepository:
    """获取审计日志仓储"""
    return AuditRepository(session)

@router.get("/logs", summary="查询审计日志", description="查询审计日志（仅管理员）", response_model=List[AuditLogResponse])
async def get_audit_logs(
    user_id: Optional[UUID] = Query(None, description="按用户ID过滤"),
    project_id: Optional[UUID] = Query(None, description="按项目ID过滤"),
    action: Optional[str] = Query(None, description="按操作类型过滤"),
    resource_type: Optional[str] = Query(None, description="按资源类型过滤"),
    start_time: Optional[datetime] = Query(None, description="开始时间"),
    end_time: Optional[datetime] = Query(None, description="结束时间"),
    skip: int = Query(0, ge=0, description="跳过记录数"),
    limit: int = Query(100, ge=1, le=1000, description="限制记录数"),
    current_user=Depends(get_current_metadata_admin),
    audit_repo: AuditRepository = Depends(get_audit_repository),
) -> List[AuditLogResponse]:
    """
    查询审计日志
    
    支持按用户、时间、操作类型等条件过滤，仅管理员可访问
    """
    logs = await audit_repo.get_logs(
        user_id=user_id,
        project_id=project_id,
        action=action,
        resource_type=resource_type,
        start_time=start_time,
        end_time=end_time,
        skip=skip,
        limit=limit
    )
    return logs

@router.get("/logs/count", summary="获取审计日志总数", description="获取审计日志总数（仅管理员）")
async def get_audit_logs_count(
    user_id: Optional[UUID] = Query(None, description="按用户ID过滤"),
    project_id: Optional[UUID] = Query(None, description="按项目ID过滤"),
    action: Optional[str] = Query(None, description="按操作类型过滤"),
    resource_type: Optional[str] = Query(None, description="按资源类型过滤"),
    start_time: Optional[datetime] = Query(None, description="开始时间"),
    end_time: Optional[datetime] = Query(None, description="结束时间"),
    current_user=Depends(get_current_metadata_admin),
    audit_repo: AuditRepository = Depends(get_audit_repository),
) -> dict:
    """
    获取审计日志总数
    
    获取符合条件的审计日志的总数，仅管理员可访问
    """
    count = await audit_repo.get_log_count(
        user_id=user_id,
        project_id=project_id,
        action=action,
        resource_type=resource_type,
        start_time=start_time,
        end_time=end_time
    )
    return {"count": count}

@router.get("/logs/my", summary="查询我的审计日志", description="查询当前用户的审计日志", response_model=List[AuditLogResponse])
async def get_my_audit_logs(
    action: Optional[str] = Query(None, description="按操作类型过滤"),
    start_time: Optional[datetime] = Query(None, description="开始时间"),
    end_time: Optional[datetime] = Query(None, description="结束时间"),
    skip: int = Query(0, ge=0, description="跳过记录数"),
    limit: int = Query(100, ge=1, le=1000, description="限制记录数"),
    current_user=Depends(get_current_metadata_user),
    audit_repo: AuditRepository = Depends(get_audit_repository),
) -> List[AuditLogResponse]:
    """
    查询当前用户的审计日志
    
    普通用户只能查看自己的操作记录
    """
    logs = await audit_repo.get_logs(
        user_id=current_user.id,
        action=action,
        start_time=start_time,
        end_time=end_time,
        skip=skip,
        limit=limit
    )
    return logs
