"""Ajoute le journal d'audit.

Revision ID: b3c7d8e9f0a1
Revises: a2b6c7d8e9f0
Create Date: 2026-08-14
"""
from alembic import op
import sqlalchemy as sa

revision = "b3c7d8e9f0a1"
down_revision = "a2b6c7d8e9f0"
branch_labels = None
depends_on = None


def upgrade():
    inspector = sa.inspect(op.get_bind())
    if "audit_logs" in inspector.get_table_names():
        # Compatibilité avec les installations où l'ancien create_all avait
        # déjà créé la table avant la prise en charge complète par Alembic.
        return
    op.create_table(
        "audit_logs",
        sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
        sa.Column("user_id", sa.Integer(), nullable=True),
        sa.Column("username", sa.String(length=80), nullable=False),
        sa.Column("action", sa.String(length=16), nullable=False),
        sa.Column("endpoint", sa.String(length=160), nullable=True),
        sa.Column("path", sa.String(length=500), nullable=False),
        sa.Column("entity_type", sa.String(length=80), nullable=True),
        sa.Column("entity_id", sa.String(length=80), nullable=True),
        sa.Column("payload", sa.Text(), nullable=True),
        sa.Column("status_code", sa.SmallInteger(), nullable=False),
        sa.Column("ip_address", sa.String(length=64), nullable=True),
        sa.Column("created_at", sa.DateTime(), nullable=False),
        sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="SET NULL"),
        sa.PrimaryKeyConstraint("id"),
    )
    for column in ("user_id", "entity_type", "entity_id", "created_at"):
        op.create_index(f"ix_audit_logs_{column}", "audit_logs", [column])


def downgrade():
    op.drop_table("audit_logs")
