"""add administrator impersonation audit log

Revision ID: 075_admin_impersonation_audits
Revises: 074_user_verification_quota
Create Date: 2026-07-10
"""

import sqlalchemy as sa
from alembic import op


revision = "075_admin_impersonation_audits"
down_revision = "074_user_verification_quota"
branch_labels = None
depends_on = None


def upgrade() -> None:
    bind = op.get_bind()
    if "admin_impersonation_audits" in set(sa.inspect(bind).get_table_names()):
        return
    op.create_table(
        "admin_impersonation_audits",
        sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
        sa.Column("operator_id", sa.BigInteger(), nullable=False),
        sa.Column("target_user_id", sa.BigInteger(), nullable=False),
        sa.Column("reason", sa.String(length=500), nullable=False),
        sa.Column("ip_address", sa.String(length=64), nullable=True),
        sa.Column("user_agent", sa.String(length=500), nullable=True),
        sa.Column("token_jti", sa.String(length=64), nullable=False),
        sa.Column("token_expires_at", sa.DateTime(timezone=True), nullable=False),
        sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
        sa.ForeignKeyConstraint(["operator_id"], ["users.id"], ondelete="RESTRICT"),
        sa.ForeignKeyConstraint(["target_user_id"], ["users.id"], ondelete="RESTRICT"),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint("token_jti", name="uq_admin_impersonation_audits_token_jti"),
    )
    op.create_index("ix_admin_impersonation_audits_operator_id", "admin_impersonation_audits", ["operator_id"])
    op.create_index("ix_admin_impersonation_audits_target_user_id", "admin_impersonation_audits", ["target_user_id"])
    op.create_index("ix_admin_impersonation_audits_created_at", "admin_impersonation_audits", ["created_at"])


def downgrade() -> None:
    bind = op.get_bind()
    if "admin_impersonation_audits" in set(sa.inspect(bind).get_table_names()):
        op.drop_table("admin_impersonation_audits")
