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

import java.io.Serializable;

import org.springframework.security.acls.AclPermissionEvaluator;
import org.springframework.security.acls.model.AclService;
import org.springframework.security.acls.model.NotFoundException;
import org.springframework.security.core.Authentication;

import com.iqser.red.service.persistence.management.v1.processor.exception.NotAllowedException;

public class CustomAclPermissionEvaluator extends AclPermissionEvaluator {

    public CustomAclPermissionEvaluator(AclService aclService) {

        super(aclService);
    }


    @Override
    public boolean hasPermission(Authentication authentication, Object domainObject, Object permission) {

        var result = super.hasPermission(authentication, domainObject, permission);
        if (!result && "VIEW_OBJECT".equals(permission)) {
            throw new NotFoundException("Object not found");
        } else if (!result && "ACCESS_OBJECT".equals(permission)) {
            throw new NotAllowedException("Access is denied");
        } else {
            return result;
        }
    }


    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {

        var result = super.hasPermission(authentication, targetId, targetType, permission);
        if (!result && "VIEW_OBJECT".equals(permission)) {
            throw new NotFoundException("Object not found");
        } else if (!result && "ACCESS_OBJECT".equals(permission)) {
            throw new NotAllowedException("Access is denied");
        } else {
            return result;
        }
    }

}
