from fastapi_modules.fastapi_leaudit.services.impl.ruleTenantScope import (
    candidate_scope_tenant_codes,
    normalize_scoped_tenant_code,
    pick_effective_scoped_row,
)


def test_candidate_scope_tenant_codes_prefers_exact_then_public_then_legacy_provincial():
    assert candidate_scope_tenant_codes("MZ") == ["MZ", "PUBLIC", "PROVINCIAL"]


def test_normalize_scoped_tenant_code_treats_empty_as_provincial_by_default():
    assert normalize_scoped_tenant_code("") == "PROVINCIAL"
    assert normalize_scoped_tenant_code(None) == "PROVINCIAL"


def test_pick_effective_scoped_row_prefers_exact_tenant():
    rows = [
        {"tenant_code": "PROVINCIAL", "id": 2},
        {"tenant_code": "MZ", "id": 1},
        {"tenant_code": "PUBLIC", "id": 3},
    ]

    result = pick_effective_scoped_row(rows, "MZ")

    assert result is not None
    assert result["id"] == 1


def test_pick_effective_scoped_row_prefers_public_over_legacy_empty_provincial_fallback():
    rows = [
        {"tenant_code": "", "id": 9},
        {"tenant_code": "PUBLIC", "id": 3},
    ]

    result = pick_effective_scoped_row(rows, "MZ")

    assert result is not None
    assert result["id"] == 3


def test_pick_effective_scoped_row_falls_back_to_public():
    rows = [
        {"tenant_code": "PUBLIC", "id": 3},
    ]

    result = pick_effective_scoped_row(rows, "MZ")

    assert result is not None
    assert result["id"] == 3
