# Copyright (c) 2024 CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com
from functools import reduce
from typing import Dict, List

from data_access_controls_iapi.api.web.types import AuthorizationContext
from data_access_controls_iapi.types import FilterType

INTERNAL_NAMESPACE = 'CZ:_Internal:'
DATA_ACCESS_DIMENSION_ID = f'{INTERNAL_NAMESPACE}DataAccessRollup'

SEPARATOR = '='
DELIMITER = '|'


def get_data_access_filter(authorization_context: AuthorizationContext) -> Dict[str, List[str]]:
    if authorization_context.data_access_controls.user_filters.filter_type == FilterType.full_access:
        return {}

    def safe(x: str, unsafe: List[str]) -> str:
        return reduce(lambda s, c: s.replace(c, '_'), unsafe, x)

    def filter_value(fqdid: str, value: str) -> str:
        return f'{DELIMITER}{safe(fqdid, [SEPARATOR, DELIMITER])}{SEPARATOR}{safe(value, [DELIMITER])}{DELIMITER}'

    data_access_filters = authorization_context.data_access_controls.user_filters.filters
    values = sorted(filter_value(fqdid, value) for fqdid, values in data_access_filters.items() for value in values)
    return {f'&{DATA_ACCESS_DIMENSION_ID}': values}
