"""Admin audit log model.

Records every sensitive admin action (logins, role changes, account
enable/disable, password resets) so the CMS can render a timeline and
satisfy audit/compliance requirements.
"""

from __future__ import annotations

from models.base import Base
from sqlalchemy import Column, DateTime, Integer, String, Text
from sqlalchemy.sql import func


class AdminAuditLog(Base):
    __tablename__ = "admin_audit_logs"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    # When the event happened. server_default=now() so the DB fills it in if
    # the app forgets; we also set it explicitly from code for correctness
    # across time zones.
    created_at = Column(
        DateTime(timezone=True), server_default=func.now(), nullable=False, index=True
    )
    # Short machine-readable action identifier, e.g. "admin.user.role_changed".
    action = Column(String(100), nullable=False, index=True)
    # The admin (or actor) who performed the action. For self-service flows
    # like "auth.login" the admin_* fields describe the actor themselves.
    admin_user_id = Column(String(255), nullable=True, index=True)
    admin_email = Column(String(255), nullable=True, index=True)
    # The user that was acted upon. May be the same as admin_* for login /
    # password-reset-completed events.
    target_user_id = Column(String(255), nullable=True, index=True)
    target_email = Column(String(255), nullable=True, index=True)
    # Free-form JSON payload (stored as TEXT to stay portable across SQLite
    # and Postgres). Use services.audit_log to serialize consistently.
    details = Column(Text, nullable=True)
    # Best-effort network metadata. Kept short to match typical IPv4/IPv6.
    ip_address = Column(String(64), nullable=True)
    user_agent = Column(String(512), nullable=True)