/***********************************************************************************************************
 * Name         : AWAL_CreateAmendmentHelper
 * Purpose      : Helper methods for awalCreateAmendment LWC
 **********************************************************************************************************/
public with sharing class AWAL_CreateAmendmentHelper {
    /**
     * @description Returns existing active amend. opportunities for the parent Opp
     * @param oppId Id of the parent Opp
     * @return List<Opportunity>    List of existing active amend. opportunities
     */
    @AuraEnabled
    public static List<Opportunity> getExistingActiveAmendments(Id oppId) {
        return [
            SELECT Id, Name
            FROM Opportunity
            WHERE Parent_Opportunity__c = :oppId AND StageName NOT IN :AWAL_Constants.OPPORTUNITY_STAGE_CLOSED_SET
        ];
    }

    @AuraEnabled
    public static Id createAmendment(Id oppId, String oppName, String leadDealmaker) {
        if (!getExistingActiveAmendments(oppId).isEmpty()) {
            throw new AuraHandledException('This opportunity already has an active Amendment.');
        }

        try {
            Decimal tcfPriorAmendments = 0;
            Decimal tcfPriorAmendmentsUSD = 0;
            String currencyIsoCode;

            List<String> checkboxesForAmendments = new List<String>(
                SchemaUtils.getFieldSetAPINames(
                        SchemaUtils.getFieldSetMembers('Opportunity', AWAL_Constants.FS_CHECKBOXES_FOR_AMENDMENTS)
                    )
                    .keySet()
            );

            String CLOSED_WON = AWAL_Constants.OPPORTUNITY_STAGE_CLOSED_WON;
            String query =
                'SELECT TotalCommittedFunding__c, TOTAL_Committed_Funding_USD__c, Deal_Type_Masters__c, CurrencyIsoCode, ' +
                String.join(checkboxesForAmendments, ',') +
                ' FROM Opportunity WHERE (Parent_Opportunity__c = :oppId OR Id = :oppId) ' +
                ' AND StageName = :CLOSED_WON ORDER BY CreatedDate DESC';

            List<Opportunity> opps = Database.query(query);
            Opportunity amendmentOpp = new Opportunity();
            Boolean shouldMirror = true;

            for (Opportunity opp : opps) {
                if (shouldMirror) {
                    for (String field : checkboxesForAmendments) {
                        amendmentOpp.put(field, opp.get(field));
                    }
                    shouldMirror = false;
                }
                if (opp.Deal_Type_Masters__c == AWAL_Constants.DEAL_TYPE_AMENDMENT_SIDE_LETTER) {
                    tcfPriorAmendments += opp.TotalCommittedFunding__c;
                    tcfPriorAmendmentsUSD += opp.TOTAL_Committed_Funding_USD__c;
                } else {
                    currencyIsoCode = opp.CurrencyIsoCode;
                }
            }

            amendmentOpp.Is_Amendment__c = true;
            amendmentOpp.Parent_Opportunity__c = oppId;
            amendmentOpp.StageName = AWAL_Constants.OPPORTUNITY_STAGE_DEAL_TRACKING;
            amendmentOpp.Name = oppName;
            amendmentOpp.Deal_Type_Masters__c = AWAL_Constants.DEAL_TYPE_AMENDMENT_SIDE_LETTER;
            amendmentOpp.OpportunityCurrency__c = currencyIsoCode;
            amendmentOpp.MaximumApprovedTerms__c = null;
            amendmentOpp.RecordTypeId = OpportunityTriggerHelper.AWAL_RECTYPE_ID;
            amendmentOpp.TCF_PriorAmendments__c = tcfPriorAmendments;
            amendmentOpp.TCF_PriorAmendments_USD__c = tcfPriorAmendmentsUSD;
            amendmentOpp.CloseDate = System.today().addDays(30);
            amendmentOpp.LeadDealmaker__c = leadDealmaker;
            amendmentOpp.DeliveryDeadlineMonths__c = null;
            amendmentOpp.ReleaseCommitmentDigitalMonths__c = null;
            amendmentOpp.IsPAndLToolAttached__c = null;

            insert amendmentOpp;
            return amendmentOpp.Id;
        } catch (Exception ex) {
            ErrorLogger.logError(ex);
            throw new AuraHandledException(ex.getMessage());
        }
    }
}