from fastapi_modules.fastapi_leaudit.services.impl.ruleTenantMaterializer import RuleTenantMaterializer
from fastapi_modules.fastapi_leaudit.services.impl.tenantServiceImpl import TenantServiceImpl


def test_rule_tenant_materializer_excludes_platform_template_tenants():
    materializer = RuleTenantMaterializer()

    tenants = [
        {"tenant_code": "PUBLIC", "is_enabled": True},
        {"tenant_code": "PROVINCIAL", "is_enabled": True},
        {"tenant_code": "MZ", "is_enabled": True},
        {"tenant_code": "JY", "is_enabled": False},
        {"tenant_code": "GZ", "is_enabled": True},
    ]

    assert materializer._filter_materializable_tenants(tenants) == ["MZ", "GZ"]


def test_rule_tenant_materializer_uses_public_as_template_source_before_legacy_provincial():
    materializer = RuleTenantMaterializer()

    assert materializer._template_source_order() == ["PUBLIC", "PROVINCIAL"]


def test_rule_tenant_materializer_builds_tenant_region_from_tenant_code():
    materializer = RuleTenantMaterializer()

    assert materializer._legacy_region_for_tenant("MZ") == "MZ"
    assert materializer._legacy_region_for_tenant("gz") == "GZ"


def test_tenant_service_exposes_rule_materializer_hook():
    service = TenantServiceImpl()

    assert service.RuleTenantMaterializer is not None


def test_rule_tenant_materializer_only_copies_versions_into_empty_tenant_rule_set():
    materializer = RuleTenantMaterializer()

    sql_text = str(materializer._materialize_versions.__code__.co_consts)

    assert "tenant_existing.rule_set_id = tenant_rs.id" in sql_text
    assert "existing.version_seq = src_v.version_seq" in sql_text
