/***********************************************************************************************************
 * Name         : RecallApprovalController
 * Purpose      : Controller for recallApproval LWC
 **********************************************************************************************************/

public without sharing class RecallApprovalController {

    /**
     * @description Recall (remove) an Approval Request
     * @param targetObjectId AdvancePayment__c ID
     * @param comments Recall comments
     */
    @AuraEnabled
    public static void recallApproval(Id targetObjectId, String comments) {
        try {
            ProcessInstanceWorkitem workItem = [
                SELECT Id
                FROM ProcessInstanceWorkitem
                WHERE ProcessInstance.TargetObjectId = :targetObjectId 
                ORDER BY CreatedDate DESC
                LIMIT 1
            ];

            List<Approval.ProcessWorkitemRequest> requests = new List<Approval.ProcessWorkitemRequest>();

            Approval.ProcessWorkitemRequest request = new Approval.ProcessWorkitemRequest();
            request.setWorkitemId(workItem.Id);
            request.setAction(AP_Constants.APPROVAL_PROCESS_ACTION_REMOVED);
            request.setComments(comments);
            requests.add(request);
    
            Approval.ProcessResult[] processResults = Approval.process(requests);
        } catch (Exception ex) {
            throw new AuraHandledException(ex.getMessage());
        }
    }

    /**
     * @description Check wheter an user is a System Admin or the initial submitter of
     * an AdvancePayment__c record
     * @param recordId AdvancePayment__c ID
     * @return Boolean indicating whether the user can recall a record or not
     */
    @AuraEnabled(cacheable=true)
    public static Boolean canRecall(Id recordId) {
        try {
            Boolean canRecall;

            ProcessInstanceWorkItem workItem = [
                SELECT ProcessInstance.SubmittedById
                FROM ProcessInstanceWorkItem
                WHERE ProcessInstance.TargetObjectId = :recordId
                ORDER BY CreatedDate DESC
                LIMIT 1
            ];

            if (workItem.ProcessInstance.SubmittedById == UserInfo.getUserId()) {
                canRecall = true;
            } else {
                Profile currentUserProfile = [
                    SELECT Name FROM Profile 
                    WHERE Id = :UserInfo.getProfileId()
                ];

                canRecall = currentUserProfile.Name == AP_Constants.SYS_ADMIN_PROFILE_NAME;
            }

            return canRecall;
        } catch (Exception ex) {
            throw new AuraHandledException(ex.getMessage());
        }
    }
}