"""affiliate reporting indexes

Revision ID: 061_affiliate_reporting_indexes
Revises: 060_user_refund_quota_logs
Create Date: 2026-06-21
"""

import sqlalchemy as sa
from alembic import op


revision = "061_affiliate_reporting_indexes"
down_revision = "060_user_refund_quota_logs"
branch_labels = None
depends_on = None


def _tables(bind) -> set[str]:
    return set(sa.inspect(bind).get_table_names())


def _index_names(bind, table_name: str) -> set[str]:
    return {index["name"] for index in sa.inspect(bind).get_indexes(table_name)}


def upgrade() -> None:
    bind = op.get_bind()
    tables = _tables(bind)

    if "affiliate_clicks" in tables:
        indexes = _index_names(bind, "affiliate_clicks")
        if "ix_affiliate_clicks_registered_user_id" not in indexes:
            op.create_index(
                "ix_affiliate_clicks_registered_user_id",
                "affiliate_clicks",
                ["registered_user_id"],
            )

    if "orders" in tables:
        indexes = _index_names(bind, "orders")
        if "ix_orders_aff_code" not in indexes:
            op.create_index("ix_orders_aff_code", "orders", ["aff_code"])


def downgrade() -> None:
    bind = op.get_bind()
    tables = _tables(bind)

    if "orders" in tables and "ix_orders_aff_code" in _index_names(bind, "orders"):
        op.drop_index("ix_orders_aff_code", table_name="orders")

    if (
        "affiliate_clicks" in tables
        and "ix_affiliate_clicks_registered_user_id" in _index_names(bind, "affiliate_clicks")
    ):
        op.drop_index("ix_affiliate_clicks_registered_user_id", table_name="affiliate_clicks")
