"""Audit log model — records all significant actions in the system."""

from __future__ import annotations

from typing import TYPE_CHECKING

from sqlalchemy import ForeignKey, Index, JSON, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.models.base import Base, TimestampMixin

if TYPE_CHECKING:
    from app.models.user import User


class AuditLog(Base, TimestampMixin):
    """One audit trail entry."""

    __tablename__ = "audit_log"

    __table_args__ = (
        Index("ix_audit_log_user_id", "user_id"),
        Index("ix_audit_log_spbu_id", "spbu_id"),
        Index("ix_audit_log_modul", "modul"),
    )

    id: Mapped[int] = mapped_column(primary_key=True)
    user_id: Mapped[int | None] = mapped_column(
        ForeignKey("master_user.id", ondelete="SET NULL"), nullable=True
    )
    spbu_id: Mapped[int | None] = mapped_column(
        ForeignKey("master_spbu.id", ondelete="SET NULL"), nullable=True
    )
    aksi: Mapped[str] = mapped_column(String(30), nullable=False)
    modul: Mapped[str] = mapped_column(String(30), nullable=False)
    object_id: Mapped[int | None] = mapped_column(nullable=True)
    detail: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    # Relationships
    user: Mapped["User | None"] = relationship(foreign_keys=[user_id])
