from datetime import datetime

from fastapi import APIRouter, Depends, status
from sqlalchemy.ext.asyncio import AsyncSession

from src.api.v1.deps import require_admin
from src.db.session import get_db
# from src.domain.models import Users
from src.db.models.app_user import AppUser
from src.domain.schemas import AuditLog, AuditLogQueryParams, BaseListResponse
from src.services.auditlog_service import AuditLogService

router = APIRouter(tags=["audit"])


@router.get(
    "/audit-logs",
    response_model=BaseListResponse[AuditLog],
    status_code=status.HTTP_200_OK,
    summary="Получение журнала аудита",
    description="Возвращает список записей аудита с возможностью фильтрации. Доступно только администраторам.",
)
async def get_audit_logs(
    db: AsyncSession = Depends(get_db),
    current_user: AppUser = Depends(require_admin),
    params: AuditLogQueryParams = Depends(),
):
    offset = (params.page - 1) * params.limit
    audit_service = AuditLogService(db)

    logs, count = await audit_service.get_all(
        user=current_user,
        limit=params.limit,
        offset=offset,
        user_id=params.user_id,
        org_unit_id=params.org_unit_id,
        task_id=params.task_id,
        form_id=params.form_id,
        event_type=params.event_type,
        event=params.event,
        date_from=datetime.combine(params.date_from, datetime.min.time()) if params.date_from else None,
        date_to=datetime.combine(params.date_to, datetime.max.time()) if params.date_to else None,
    )
    
    result = [audit_service.orm_log_to_response(log) for log in logs]
    return BaseListResponse(result=result, count=count)
