"""loyalty 004 - relax card uniqueness for cross-location support

Replace the (merchant_id, customer_id) and (customer_id, program_id)
unique indexes with (enrolled_at_store_id, customer_id). This allows
merchants with cross-location redemption DISABLED to issue one card per
store per customer, while merchants with it ENABLED enforce the
per-merchant constraint in the application layer.

Revision ID: loyalty_004
Revises: loyalty_003
Create Date: 2026-04-10
"""
from alembic import op

revision = "loyalty_004"
down_revision = "loyalty_003"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # Drop the old per-merchant unique indexes
    op.drop_index("idx_loyalty_card_merchant_customer", table_name="loyalty_cards")
    op.drop_index("idx_loyalty_card_customer_program", table_name="loyalty_cards")

    # Keep a non-unique index on (merchant_id, customer_id) for lookups
    op.create_index(
        "idx_loyalty_card_merchant_customer",
        "loyalty_cards",
        ["merchant_id", "customer_id"],
        unique=False,
    )

    # New unique constraint: one card per customer per store (always valid)
    op.create_index(
        "idx_loyalty_card_store_customer",
        "loyalty_cards",
        ["enrolled_at_store_id", "customer_id"],
        unique=True,
    )


def downgrade() -> None:
    op.drop_index("idx_loyalty_card_store_customer", table_name="loyalty_cards")
    op.drop_index("idx_loyalty_card_merchant_customer", table_name="loyalty_cards")

    # Restore original unique indexes
    op.create_index(
        "idx_loyalty_card_merchant_customer",
        "loyalty_cards",
        ["merchant_id", "customer_id"],
        unique=True,
    )
    op.create_index(
        "idx_loyalty_card_customer_program",
        "loyalty_cards",
        ["customer_id", "program_id"],
        unique=True,
    )
