from fmatch.saas.utils.soql_rewriter import enforce_row_limit, add_suggested_fixes


def test_enforce_row_limit_adds_order_by_when_limit_already_present():
    soql = "SELECT Id, Name FROM Account LIMIT 50"
    rewritten, modified, message = enforce_row_limit(soql, max_rows=100, tier="free")

    assert modified is True
    assert "ORDER BY Id LIMIT 50" in rewritten
    assert message and "ORDER BY Id" in message


def test_enforce_row_limit_adds_limit_and_order_by_for_unbounded_query():
    soql = "SELECT Id, Name FROM Account"
    rewritten, modified, message = enforce_row_limit(soql, max_rows=200, tier="free")

    assert modified is True
    assert rewritten.endswith("ORDER BY Id LIMIT 200")
    assert message and "LIMIT 200" in message and "ORDER BY Id" in message


def test_add_suggested_fixes_inserts_where_before_order_by_and_limit():
    soql = "SELECT Id, Name FROM Account ORDER BY Name LIMIT 100"
    fixes = add_suggested_fixes(soql, tier="free", max_rows=200)
    where_fix = next((fix for fix in fixes if fix.get("fix_type") == "add_where_clause"), None)

    assert where_fix is not None
    assert (
        where_fix["suggested_soql"]
        == "SELECT Id, Name FROM Account WHERE CreatedDate >= LAST_N_DAYS:30 ORDER BY Name LIMIT 100"
    )
