from .....utils import get_dict_value
from ..builder import build_json_permission_reference
from ..dto import JsonPermission, JsonPermissionRule


def verify_rule_verification(
    rule: JsonPermissionRule,
    parameters: dict,
) -> bool:
    field = get_dict_value(rule.params, "field")
    action = get_dict_value(rule.params, "action")
    data = get_dict_value(rule.params, "data")

    field_reference = build_json_permission_reference(field)
    field_value = get_dict_value(parameters, path=[field_reference.type, field_reference.field])

    data_value = data
    if isinstance(data_value, dict) and get_dict_value(data_value, "type"):
        data_value = build_json_permission_reference(data_value)
        data_value = get_dict_value(parameters, path=[data_value.type, data_value.field])

    if action == "containsOne":
        return any(item in (field_value or []) for item in (data_value or []))
    elif action == "containsAll":
        return all(item in (field_value or []) for item in (data_value or []))

    raise NotImplementedError(f"Verification of action {action} not implemented")


def verify_rule(
    rule: JsonPermissionRule,
    parameters: dict,
) -> bool:
    if rule.type == "verification":
        authorized = verify_rule_verification(rule=rule, parameters=parameters)
        return authorized
    raise NotImplementedError(f"Type {rule.type} not implemented")


def verify_permission(
    permission: JsonPermission,
    parameters: dict,
) -> bool:
    for i, rule in enumerate(permission.rules):
        if not verify_rule(
            rule=rule,
            parameters=parameters,
        ):
            return False
    return True
