from auraindex.analyzers.sql_ast import analyze_sql_candidates
from auraindex.models import QueryCandidate, QueryContext


def test_sql_ast_analysis_extracts_table_and_column_signals() -> None:
    candidate = QueryCandidate(
        sql=(
            "SELECT u.id FROM users u "
            "JOIN orders o ON u.id = o.user_id "
            "WHERE u.status = ? AND u.email = ? "
            "ORDER BY u.created_at DESC"
        ),
        context=QueryContext(
            file_path="sample.py",
            line=10,
            function="handler",
            language="python",
            source_kind="raw_sql",
        ),
    )

    parsed, failures = analyze_sql_candidates([candidate], dialect="postgres")
    assert not failures
    assert len(parsed) == 1

    features = parsed[0]
    assert features.statement_kind == "select"
    assert "users" in features.tables
    assert "orders" in features.tables
    assert ("users", "status") in features.where_columns
    assert any(pair == ("orders", "user_id") for pair in features.join_columns)


def test_sql_ast_falls_back_to_mysql_dialect_when_needed() -> None:
    candidate = QueryCandidate(
        sql="SELECT `id` FROM `admins` WHERE `email` = 'a@example.com'",
        context=QueryContext(
            file_path="dump.sql",
            line=20,
            function=None,
            language="sql",
            source_kind="sql_file",
        ),
    )

    parsed, failures = analyze_sql_candidates([candidate], dialect="postgres")
    assert not failures
    assert len(parsed) == 1
    assert parsed[0].tables == ["admins"]
    assert candidate.metadata.get("parsed_dialect") == "mysql"
