"""
Schema contract tests: verify all 5 required indexes exist.

Uses pytest's `db` fixture (creates schema via db.create_all(), which respects
__table_args__ Index definitions — no migration required for tests).

AR-5: idx_transactions_date, idx_transactions_category, idx_transactions_account,
      idx_bills_due_date, idx_balance_updates_account
"""
from sqlalchemy import text


REQUIRED_INDEXES = [
    'idx_transactions_date',
    'idx_transactions_category',
    'idx_transactions_account',
    'idx_bills_due_date',
    'idx_balance_updates_account',
]


def _get_index_names(db_session):
    """Query sqlite_master for all user-defined indexes."""
    rows = db_session.execute(
        text("SELECT name FROM sqlite_master WHERE type='index'")
    ).fetchall()
    return {row[0] for row in rows}


def test_idx_transactions_date_exists(db):
    assert 'idx_transactions_date' in _get_index_names(db.session)


def test_idx_transactions_category_exists(db):
    assert 'idx_transactions_category' in _get_index_names(db.session)


def test_idx_transactions_account_exists(db):
    assert 'idx_transactions_account' in _get_index_names(db.session)


def test_idx_bills_due_date_exists(db):
    assert 'idx_bills_due_date' in _get_index_names(db.session)


def test_idx_balance_updates_account_exists(db):
    assert 'idx_balance_updates_account' in _get_index_names(db.session)


def test_all_required_indexes_exist(db):
    """Aggregate: all 5 AR-5 indexes present in schema."""
    found = _get_index_names(db.session)
    missing = [idx for idx in REQUIRED_INDEXES if idx not in found]
    assert missing == [], f"Missing required indexes: {missing}"
