from pathlib import Path

from auraindex.pipeline import ScanConfig, run_scan


def test_query_advisories_detect_common_select_antipatterns(tmp_path: Path) -> None:
    sample = tmp_path / "queries.sql"
    sample.write_text(
        """
SELECT * FROM users WHERE name LIKE '%abc%';
SELECT id FROM users WHERE status = 'active' ORDER BY created_at DESC;
""".strip(),
        encoding="utf-8",
    )

    result = run_scan(
        ScanConfig(
            target_path=tmp_path,
            dialect="postgres",
            extensions={".sql"},
            min_support=1,
            max_indexes_per_table=4,
        )
    )

    advisory_meta = result.metadata.get("query_advisories", {})
    items = advisory_meta.get("items", [])
    assert items
    rule_ids = {item["rule_id"] for item in items}
    assert "select_star" in rule_ids
    assert "order_by_without_limit" in rule_ids or "leading_wildcard_like" in rule_ids


def test_schema_drift_reports_possibly_unused_existing_index(tmp_path: Path) -> None:
    sample = tmp_path / "schema_and_queries.sql"
    sample.write_text(
        """
CREATE INDEX IF NOT EXISTS ix_users_status ON users (status);
SELECT id FROM users WHERE email = 'a@example.com';
""".strip(),
        encoding="utf-8",
    )

    result = run_scan(
        ScanConfig(
            target_path=tmp_path,
            dialect="postgres",
            extensions={".sql"},
            min_support=1,
            max_indexes_per_table=4,
            enable_schema_checks=False,
        )
    )

    drift = result.metadata.get("schema_drift", {})
    summary = drift.get("summary", {})
    assert summary.get("possibly_unused_existing_indexes", 0) >= 1
