from auraindex.analyzers.index_suggester import suggest_indexes
from auraindex.analyzers.sql_ast import analyze_sql_candidates
from auraindex.analyzers.workload import build_workload_stats
from auraindex.models import QueryCandidate, QueryContext


def test_index_suggester_emits_composite_and_join_candidates() -> None:
    context = QueryContext(
        file_path="repo/orders.py",
        line=1,
        function="query_orders",
        language="python",
        source_kind="raw_sql",
    )
    candidates = [
        QueryCandidate(
            sql="SELECT * FROM orders WHERE user_id = ? AND status = ? ORDER BY created_at DESC",
            context=context,
        ),
        QueryCandidate(
            sql="SELECT id FROM orders WHERE user_id = ? AND status = ?",
            context=context,
        ),
        QueryCandidate(
            sql=(
                "SELECT o.id FROM orders o JOIN users u ON o.user_id = u.id "
                "WHERE u.email = ?"
            ),
            context=context,
        ),
    ]

    parsed, failures = analyze_sql_candidates(candidates, dialect="postgres")
    assert not failures
    workload = build_workload_stats(parsed)
    suggestions = suggest_indexes(workload, dialect="postgres", min_support=2, max_indexes_per_table=4)

    order_suggestions = [suggestion for suggestion in suggestions if suggestion.table == "orders"]
    assert order_suggestions
    assert any("impact" in suggestion.metadata for suggestion in suggestions)
    assert any("index_type" in suggestion.metadata for suggestion in suggestions)
    assert any(suggestion.columns[:2] == ["user_id", "status"] for suggestion in order_suggestions)
    assert any(suggestion.kind in {"join_key", "composite_filter", "composite_order"} for suggestion in suggestions)
