"""create admin_audit_logs table

Revision ID: e9a7b2c4d6f8
Revises: d8e4f1a2c3b5
Create Date: 2026-05-02 10:00:00.000000

"""
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision: str = "e9a7b2c4d6f8"
down_revision: Union[str, Sequence[str], None] = "d8e4f1a2c3b5"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def _has_table(table: str) -> bool:
    bind = op.get_bind()
    inspector = sa.inspect(bind)
    return inspector.has_table(table)


def upgrade() -> None:
    """Create the admin_audit_logs table and supporting indexes."""
    if not _has_table("admin_audit_logs"):
        op.create_table(
            "admin_audit_logs",
            sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
            sa.Column(
                "created_at",
                sa.DateTime(timezone=True),
                server_default=sa.func.now(),
                nullable=False,
            ),
            sa.Column("action", sa.String(length=100), nullable=False),
            sa.Column("admin_user_id", sa.String(length=255), nullable=True),
            sa.Column("admin_email", sa.String(length=255), nullable=True),
            sa.Column("target_user_id", sa.String(length=255), nullable=True),
            sa.Column("target_email", sa.String(length=255), nullable=True),
            sa.Column("details", sa.Text(), nullable=True),
            sa.Column("ip_address", sa.String(length=64), nullable=True),
            sa.Column("user_agent", sa.String(length=512), nullable=True),
            sa.PrimaryKeyConstraint("id"),
        )
        op.create_index(
            "ix_admin_audit_logs_created_at", "admin_audit_logs", ["created_at"]
        )
        op.create_index("ix_admin_audit_logs_action", "admin_audit_logs", ["action"])
        op.create_index(
            "ix_admin_audit_logs_admin_user_id", "admin_audit_logs", ["admin_user_id"]
        )
        op.create_index(
            "ix_admin_audit_logs_admin_email", "admin_audit_logs", ["admin_email"]
        )
        op.create_index(
            "ix_admin_audit_logs_target_user_id", "admin_audit_logs", ["target_user_id"]
        )
        op.create_index(
            "ix_admin_audit_logs_target_email", "admin_audit_logs", ["target_email"]
        )


def downgrade() -> None:
    """Drop the admin_audit_logs table."""
    if _has_table("admin_audit_logs"):
        for idx in (
            "ix_admin_audit_logs_target_email",
            "ix_admin_audit_logs_target_user_id",
            "ix_admin_audit_logs_admin_email",
            "ix_admin_audit_logs_admin_user_id",
            "ix_admin_audit_logs_action",
            "ix_admin_audit_logs_created_at",
        ):
            try:
                op.drop_index(idx, table_name="admin_audit_logs")
            except Exception:  # noqa: BLE001
                pass
        op.drop_table("admin_audit_logs")