from fastapi_modules.fastapi_leaudit.services.impl.auditServiceImpl import (
    _candidate_binding_tenant_codes,
    _pick_effective_binding,
)


def test_candidate_binding_tenant_codes_prefers_tenant_then_public_then_legacy_provincial():
    assert _candidate_binding_tenant_codes("MZ") == ["MZ", "PUBLIC", "PROVINCIAL"]


def test_candidate_binding_tenant_codes_deduplicates_special_tenant_values():
    assert _candidate_binding_tenant_codes("PROVINCIAL") == ["PUBLIC", "PROVINCIAL"]
    assert _candidate_binding_tenant_codes("PUBLIC") == ["PUBLIC"]


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

    result = _pick_effective_binding(bindings, "MZ")

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


def test_pick_effective_binding_falls_back_to_public_then_legacy_provincial():
    provincial_only = [
        {"tenant_code": "PROVINCIAL", "id": 2},
        {"tenant_code": "PUBLIC", "id": 3},
    ]
    public_only = [
        {"tenant_code": "PUBLIC", "id": 3},
    ]

    provincial_result = _pick_effective_binding(provincial_only, "MZ")
    public_result = _pick_effective_binding(public_only, "MZ")

    assert provincial_result is not None
    assert provincial_result["id"] == 3
    assert public_result is not None
    assert public_result["id"] == 3


def test_pick_effective_binding_handles_legacy_empty_tenant_as_global_fallback():
    bindings = [
        {"tenant_code": "", "id": 9},
    ]

    result = _pick_effective_binding(bindings, "MZ")

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