"""add composite indexes for paginated audit queries

Revision ID: c2d3e4f5a6b7
Revises: b1c2d3e4f5a6
Create Date: 2026-06-15 17:30:00.000000
"""
from __future__ import annotations

from alembic import op
import sqlalchemy as sa

revision = "c2d3e4f5a6b7"
down_revision = "b1c2d3e4f5a6"
branch_labels = None
depends_on = None

INDEXES: tuple[tuple[str, list[str]], ...] = (
    ("ix_audit_log_scope_created_at", ["scope", "created_at"]),
    ("ix_audit_log_tenant_scope_created_at", ["tenant_id", "scope", "created_at"]),
)


def upgrade() -> None:
    bind = op.get_bind()
    inspector = sa.inspect(bind)
    if "audit_log" not in inspector.get_table_names():
        return
    existing = {index["name"] for index in inspector.get_indexes("audit_log")}
    for name, columns in INDEXES:
        if name not in existing:
            op.create_index(name, "audit_log", columns)


def downgrade() -> None:
    bind = op.get_bind()
    inspector = sa.inspect(bind)
    if "audit_log" not in inspector.get_table_names():
        return
    existing = {index["name"] for index in inspector.get_indexes("audit_log")}
    for name, _columns in reversed(INDEXES):
        if name in existing:
            op.drop_index(name, table_name="audit_log")
