package com.eactive.eai.rms.onl.apim.approval;

import com.eactive.apim.portal.approval.entity.Approval;
import com.eactive.apim.portal.approval.entity.Approver;
import com.eactive.apim.portal.approval.entity.ApproverStatus;
import com.eactive.apim.portal.approval.statemachine.ApprovalAuthorizer;
import org.springframework.stereotype.Component;

@Component
public class PortalApprovalAuthorizer implements ApprovalAuthorizer {

    @Override
    public boolean isAuthorized(Approval approval, String approverId) {
        return approval.getApprovers().stream()
            .filter(this::isCurrentApprover)
            .map(this::getApproverId)
            .filter(java.util.Objects::nonNull)
            .anyMatch(id -> id.equals(approverId));
    }

    private boolean isCurrentApprover(Approver approver) {
        return ApproverStatus.CURRENT.equals(approver.getApproverStatus());
    }

    private String getApproverId(Approver approver) {
        return approver.getUser() != null ? approver.getUser().getId() : null;
    }
}
