"""Audit log viewer router (admin only)."""

from datetime import datetime
from typing import Optional

from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from app.database import get_db
from app.dependencies.auth import require_role
from app.models.user import User
from app.schemas.audit import AuditLogOut, AuditLogPage
from app.services.audit_query_service import (
    list_distinct_actions,
    list_distinct_entity_types,
    list_logs,
)

router = APIRouter(prefix="/audit-logs", tags=["audit"])


@router.get("", response_model=AuditLogPage)
def list_audit_logs(
    user_id: Optional[str] = Query(None, description="Filter by user ID"),
    action: Optional[str] = Query(None, description="Filter by action type"),
    entity_type: Optional[str] = Query(None, description="Filter by entity type"),
    start_date: Optional[datetime] = Query(None, description="Filter by start date"),
    end_date: Optional[datetime] = Query(None, description="Filter by end date"),
    offset: int = Query(0, ge=0, description="Number of records to skip"),
    limit: int = Query(50, ge=1, le=100, description="Max records to return"),
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role("admin")),
):
    """Return paginated audit logs with optional filters.

    **Requires admin role.**
    """
    result = list_logs(
        db,
        user_id=user_id,
        action=action,
        entity_type=entity_type,
        start_date=start_date,
        end_date=end_date,
        offset=offset,
        limit=limit,
    )
    return AuditLogPage(
        items=[AuditLogOut(**item) for item in result["items"]],
        total=result["total"],
        offset=result["offset"],
        limit=result["limit"],
    )


@router.get("/actions", response_model=list[str])
def list_actions(
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role("admin")),
):
    """Return a list of distinct action types in the audit log.

    **Requires admin role.**
    """
    return list_distinct_actions(db)


@router.get("/entity-types", response_model=list[str])
def list_entity_types(
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role("admin")),
):
    """Return a list of distinct entity types in the audit log.

    **Requires admin role.**
    """
    return list_distinct_entity_types(db)
