"""Add impersonation_log table for admin impersonation audit trail.

Revision ID: 018_add_impersonation_log
Revises: 017_add_consent_tables
"""

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID


revision = "018_add_impersonation_log"
down_revision = "017_add_consent_tables"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "impersonation_log",
        sa.Column("id", UUID(as_uuid=True), primary_key=True, server_default=sa.text("gen_random_uuid()")),
        sa.Column("admin_user_id", UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
        sa.Column("target_user_id", UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
        sa.Column("action", sa.String(10), nullable=False),  # 'start' or 'stop'
        sa.Column("ip_address", sa.String(45), nullable=True),
        sa.Column("created_at", sa.DateTime, server_default=sa.func.now(), nullable=False),
    )
    op.create_index("ix_impersonation_log_admin", "impersonation_log", ["admin_user_id"])
    op.create_index("ix_impersonation_log_target", "impersonation_log", ["target_user_id"])
    op.create_index("ix_impersonation_log_created", "impersonation_log", ["created_at"])


def downgrade() -> None:
    op.drop_index("ix_impersonation_log_created")
    op.drop_index("ix_impersonation_log_target")
    op.drop_index("ix_impersonation_log_admin")
    op.drop_table("impersonation_log")
