"""AuditLog model — immutable, hash-chained event record.

Each entry references the previous entry's hash (``hash_prev``) so any tampering
breaks the chain from that point forward. ``seq`` gives a deterministic
per-workspace ordering independent of timestamp resolution.
"""

from __future__ import annotations

import uuid

from sqlalchemy import JSON, BigInteger, Index, String, Uuid
from sqlalchemy.orm import Mapped, mapped_column

from legate.db.base import Base, TimestampMixin, UUIDPrimaryKeyMixin


class AuditLog(UUIDPrimaryKeyMixin, TimestampMixin, Base):
    __tablename__ = "audit_logs"
    __table_args__ = (Index("ix_audit_ws_seq", "workspace_id", "seq", unique=True),)

    workspace_id: Mapped[uuid.UUID] = mapped_column(Uuid, index=True, nullable=False)
    # Monotonic per-workspace sequence number, assigned in the application layer.
    seq: Mapped[int] = mapped_column(BigInteger, nullable=False)
    # Who performed the action: "user:<id>", "apikey:<id>", or "system".
    actor: Mapped[str] = mapped_column(String(255), nullable=False)
    action: Mapped[str] = mapped_column(String(255), nullable=False)
    target: Mapped[str | None] = mapped_column(String(512), nullable=True)
    event_metadata: Mapped[dict] = mapped_column("metadata", JSON, nullable=False, default=dict)
    hash_prev: Mapped[str | None] = mapped_column(String(64), nullable=True)
    hash: Mapped[str] = mapped_column(String(64), nullable=False)

    def __repr__(self) -> str:  # pragma: no cover - debug helper
        return f"<AuditLog ws={self.workspace_id} seq={self.seq} action={self.action}>"
