"""Audit router: read the workspace's audit log (requires VIEW)."""

from __future__ import annotations

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

from legate.api.deps import Principal, require
from legate.api.schemas import AuditOut
from legate.db.session import get_db
from legate.policy.rbac import Permission
from legate.repositories import audit as audit_repo

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


@router.get("", response_model=list[AuditOut])
def list_audit(
    limit: int = Query(default=100, ge=1, le=500),
    offset: int = Query(default=0, ge=0),
    principal: Principal = Depends(require(Permission.VIEW)),
    db: Session = Depends(get_db),
) -> list[AuditOut]:
    entries = audit_repo.list_for_workspace(
        db, workspace_id=principal.workspace_id, limit=limit, offset=offset
    )
    return [
        AuditOut(
            id=e.id,
            seq=e.seq,
            actor=e.actor,
            action=e.action,
            target=e.target,
            metadata=e.event_metadata or {},
            hash=e.hash,
            hash_prev=e.hash_prev,
            created_at=e.created_at,
        )
        for e in entries
    ]
