from __future__ import annotations

from datetime import datetime

from sqlalchemy import (
    BigInteger,
    DateTime,
    ForeignKey,
    Index,
    JSON,
    String,
    func,
    text,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship

from src.db.base import Base


class AuditLog(Base):
    __tablename__ = "audit_log"
    __table_args__ = (
        Index("ix_v3_audit_log_dt", text("event_dt DESC")),
        Index("ix_v3_audit_log_event", "event"),
        Index(
            "ix_v3_audit_log_form",
            "form_id",
            postgresql_where="form_id IS NOT NULL",
        ),
        Index("ix_v3_audit_log_user", "user_id"),
        Index("ix_v4_audit_log_dt", text("event_dt DESC")),
        Index("ix_v4_audit_log_event", "event"),
        Index(
            "ix_v4_audit_log_form",
            "form_id",
            postgresql_where="form_id IS NOT NULL",
        ),
        Index("ix_v4_audit_log_user", "user_id"),
        {"schema": "v3"},
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    user_id: Mapped[int | None] = mapped_column(
        ForeignKey("v3.app_user.id", ondelete="SET NULL")
    )
    org_unit_id: Mapped[int | None] = mapped_column(
        ForeignKey("v3.org_unit.id", ondelete="SET NULL")
    )
    task_id: Mapped[int | None] = mapped_column()
    form_id: Mapped[int | None] = mapped_column()
    event_dt: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()
    )
    event: Mapped[str] = mapped_column(String)
    event_type: Mapped[str] = mapped_column(String)
    event_data: Mapped[dict | None] = mapped_column(JSON)

    user: Mapped["AppUser | None"] = relationship(
        "AppUser", back_populates="audit_logs"
    )
#     org_unit: Mapped["OrgUnit | None"] = relationship(
#         "OrgUnit", back_populates="audit_logs"
#     )
