package com.iqser.red.service.persistence.management.v1.processor.acl.custom.initializer;

import static com.iqser.red.service.persistence.management.v1.processor.acl.custom.constants.CustomPermissionConstants.EVERYONE_ELSE;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.iqser.red.service.persistence.management.v1.processor.acl.RedPermission;
import com.iqser.red.service.persistence.management.v1.processor.acl.custom.service.CustomPermissionService;
import com.iqser.red.service.persistence.service.v1.api.shared.model.permission.CustomPermissionMappingModel;
import com.iqser.red.service.persistence.service.v1.api.shared.model.permission.CustomPermissionModel;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@RequiredArgsConstructor
public class CustomDossierPermissionsACLInitializer implements IACLInitializer {

    private static final String TARGET_OBJECT = "Dossier";
    private final CustomPermissionService customPermissionService;


    public void initialize() {

        if (customPermissionService.getCustomPermissionMappings(TARGET_OBJECT).isEmpty()) {

            log.info("No custom permissions seeded. Adding defaults!");

            List<CustomPermissionMappingModel> mappingModels = new ArrayList<>();

            var viewObjectPermission = convert(RedPermission.VIEW_OBJECT);
            var viewObjectMappedPermissions = List.of(convert(RedPermission.OWNER), convert(RedPermission.APPROVE), convert(RedPermission.REVIEW), EVERYONE_ELSE);

            mappingModels.add(new CustomPermissionMappingModel(viewObjectPermission, viewObjectMappedPermissions));

            var accessObjectPermission = convert(RedPermission.ACCESS_OBJECT);
            var accessObjectMappedPermissions = List.of(convert(RedPermission.OWNER), convert(RedPermission.APPROVE), convert(RedPermission.REVIEW), EVERYONE_ELSE);

            mappingModels.add(new CustomPermissionMappingModel(accessObjectPermission, accessObjectMappedPermissions));

            customPermissionService.saveCustomPermissionMappings(TARGET_OBJECT, mappingModels);

        }

        customPermissionService.syncAllCustomPermissions();
    }


    @Override
    public int sort() {

        return 10;
    }


    private CustomPermissionModel convert(RedPermission redPermission) {

        return new CustomPermissionModel(redPermission.getMask(), redPermission.getName(), redPermission.getSort(), redPermission.isChangeable());
    }

}
