from fastapi_common.fastapi_common_web.domain.responses import StatusCodeEnum
from fastapi_common.fastapi_common_web.exception.LeauditException import LeauditException

from fastapi_modules.fastapi_leaudit.services.impl.evaluationPointGroupServiceImpl import (
    EvaluationPointGroupServiceImpl,
)


def test_binding_scope_payload_for_tenant_user_uses_exact_tenant():
    service = EvaluationPointGroupServiceImpl()

    payload = service._build_binding_scope_payload(
        current_user={"tenant_code": "MZ", "tenant_name": "梅州", "is_global": False},
        rule_set_meta={"effective_tenant_code": "PROVINCIAL", "effective_scope_type": "PROVINCIAL"},
    )

    assert payload == {
        "tenant_code": "MZ",
        "scope_type": "TENANT",
        "tenant_name_snapshot": "梅州",
    }


def test_binding_scope_payload_for_global_user_inherits_rule_set_scope():
    service = EvaluationPointGroupServiceImpl()

    payload = service._build_binding_scope_payload(
        current_user={"tenant_code": None, "tenant_name": None, "is_global": True},
        rule_set_meta={"effective_tenant_code": "PUBLIC", "effective_scope_type": "PUBLIC"},
    )

    assert payload == {
        "tenant_code": "PUBLIC",
        "scope_type": "PUBLIC",
        "tenant_name_snapshot": None,
    }


def test_binding_scope_payload_rejects_tenant_user_binding_public_asset():
    service = EvaluationPointGroupServiceImpl()

    try:
        service._build_binding_scope_payload(
            current_user={"tenant_code": "MZ", "tenant_name": "梅州", "is_global": False},
            rule_set_meta={"effective_tenant_code": "PUBLIC", "effective_scope_type": "PUBLIC"},
        )
        assert False, "expected LeauditException"
    except LeauditException as exc:
        assert exc.status == StatusCodeEnum.HTTP_403_FORBIDDEN


def test_binding_inheritance_state_marks_tenant_user_using_provincial_binding_as_inherited():
    service = EvaluationPointGroupServiceImpl()

    state = service._build_binding_scope_state(
        binding_row={"tenant_code": "PROVINCIAL", "scope_type": "PROVINCIAL"},
        current_user={"tenant_code": "MZ", "is_global": False},
        rule_set_meta={"source_rule_set_id": 88},
    )

    assert state["effective_tenant_code"] == "PROVINCIAL"
    assert state["effective_scope_type"] == "PROVINCIAL"
    assert state["is_inherited"] is True
    assert state["source_rule_set_id"] == 88

