"""add entitlement renewal idempotency and expiry index

Revision ID: 0026_entitlement_renewal
Revises: 0025_recent_practice_review
"""

from __future__ import annotations

from alembic import context, op
import sqlalchemy as sa


revision = "0026_entitlement_renewal"
down_revision = "0025_recent_practice_review"
branch_labels = None
depends_on = None


def upgrade() -> None:
    inspector = None if context.is_offline_mode() else sa.inspect(op.get_bind())
    log_columns = set() if inspector is None else {
        column["name"] for column in inspector.get_columns("sys_user_entitlement_log")
    }
    if "request_key" not in log_columns:
        op.add_column("sys_user_entitlement_log", sa.Column("request_key", sa.String(160), nullable=True))

    log_indexes = set() if inspector is None else {
        index["name"] for index in inspector.get_indexes("sys_user_entitlement_log")
    }
    if "ux_entitlement_log_request_key" not in log_indexes:
        op.create_index(
            "ux_entitlement_log_request_key",
            "sys_user_entitlement_log",
            ["request_key"],
            unique=True,
        )

    entitlement_indexes = set() if inspector is None else {
        index["name"] for index in inspector.get_indexes("sys_user_entitlement")
    }
    if "ix_entitlement_status_expiry" not in entitlement_indexes:
        op.create_index(
            "ix_entitlement_status_expiry",
            "sys_user_entitlement",
            ["status", "expired_at", "user_id"],
        )


def downgrade() -> None:
    op.drop_index("ix_entitlement_status_expiry", table_name="sys_user_entitlement")
    op.drop_index("ux_entitlement_log_request_key", table_name="sys_user_entitlement_log")
    op.drop_column("sys_user_entitlement_log", "request_key")
