"""Migration metadata tests."""
from pathlib import Path

from alembic.config import Config
from alembic.script import ScriptDirectory


def test_alembic_revisions_exist():
    root = Path(__file__).resolve().parents[2]
    cfg = Config(str(root / "alembic.ini"))
    cfg.set_main_option("script_location", str(root / "alembic"))
    scripts = ScriptDirectory.from_config(cfg)
    revisions = list(scripts.walk_revisions())
    assert revisions
    assert revisions[0].revision == "0007_phase_76_wallet"
    assert revisions[-1].revision == "0001_initial"
    assert revisions[0].down_revision == "0006_phase_75_referral"
    assert revisions[-1].down_revision is None


def test_migration_upgrade_creates_metadata_tables(db_setup):
    from app.core.database import Base
    import app.models  # noqa: F401

    expected = {
        "loyalty_programs",
        "membership_tiers",
        "members",
        "point_accounts",
        "rewards",
        "campaigns",
        "loyalty_audit_logs",
        "outbox_events",
        "membership_lifecycle_events",
        "point_ledger_entries",
        "reward_redemptions",
        "campaign_applications",
        "referral_programs",
        "referral_codes",
        "referral_attributions",
        "wallet_accounts",
        "wallet_ledger_entries",
    }
    assert expected.issubset(set(Base.metadata.tables.keys()))
    assert "ix_members_tenant_tier" in {
        idx.name for table in Base.metadata.tables.values() for idx in table.indexes
    }