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

import java.io.Serializable;

import org.springframework.security.acls.domain.ObjectIdentityImpl;
import org.springframework.security.acls.model.AlreadyExistsException;
import org.springframework.security.acls.model.MutableAcl;
import org.springframework.security.acls.model.MutableAclService;
import org.springframework.security.acls.model.NotFoundException;

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

@Slf4j
@RequiredArgsConstructor
public abstract class AbstractACLService<ID extends Serializable> {

    protected final MutableAclService mutableAclService;


    public MutableAcl getOrCreateACL(Serializable id) {

        var objectIdentity = new ObjectIdentityImpl(getIdentifier(), id);
        try {
            return (MutableAcl) mutableAclService.readAclById(objectIdentity);
        } catch (NotFoundException e) {
            try {
                return mutableAclService.createAcl(objectIdentity);
            } catch (AlreadyExistsException e1) {
                // This happened always for the same dossierId repeatedly in an endless loop triggered by SyncUserPermissionsJob every 2 mins on prod stack till it broke the stack,
                // so I don't think it was any kind of race condition.
                // Maybe this happens due corrupt entries.
                log.warn("Recreate already existing acl object {}", objectIdentity);
                mutableAclService.deleteAcl(objectIdentity, true);
                return mutableAclService.createAcl(objectIdentity);
            }
        }
    }


    public abstract String getIdentifier();

}
