public with sharing class BatchApexErrorEventTriggerHelper {
    @TestVisible
    private static Messaging.SingleEmailMessage emailSent = null;

    /**
     * @description Handles BatchApexErrorEvents created by TempFormResponseBatch class.
     *  It updates TFR impacted records' Times_Processed__c field increasing its value by 1
     * @param  List<BatchApexErrorEvent>    events to process
     */
    public static void handleTempFormResponseBatchJob(List<BatchApexErrorEvent> events) {
        try {
            Set<String> tfrIds = new Set<String>();
            List<BatchApexErrorEventLog> errorEventLogs = new List<BatchApexErrorEventLog>();

            for (BatchApexErrorEvent event : events) {
                if (String.isNotBlank(event.JobScope)) {
                    tfrIds.addAll(event.JobScope.split(','));
                }

                errorEventLogs.add(new BatchApexErrorEventLog(event.Message, event.ExceptionType, event.StackTrace));
            }

            if (!errorEventLogs.isEmpty()) {
                SMELogger.logError(errorEventLogs);
            }

            if (!tfrIds.isEmpty()) {
                List<Temp_Form_Response__c> tfrsToUpdate = new List<Temp_Form_Response__c>();
                Map<Id, Temp_Form_Response__c> tfrRecords = new Map<Id, Temp_Form_Response__c>(
                    [SELECT Id, Times_Processed__c FROM Temp_Form_Response__c WHERE Id IN :tfrIds]
                );

                for (String tfrId : tfrIds) {
                    Temp_Form_Response__c tfr = tfrRecords.get(tfrId);
                    if (tfr != null) {
                        tfr.Times_Processed__c = tfr.Times_Processed__c + 1;
                        tfrsToUpdate.add(tfr);
                    }
                }
                if (!tfrsToUpdate.isEmpty()) {
                    Database.update(tfrsToUpdate, false);
                }
            }
        } catch (Exception ex) {
            SMELogger.logError(ex);
        }
    }

    /**
     * @description Sends an email informing the events that caused the job failure
     * @param   String  batch job class name
     * @param   List<BatchApexErrorEvent>   events to process
     */
    public static void handleGenericBatchJob(String className, List<BatchApexErrorEvent> events) {
        try {
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            email.setToAddresses(
                ConfigUtils.getConfigMultipleStrings(ConfigUtils.BATCH_FAILURE_ALERT_EMAIL_RECIPIENTS)
            );
            email.setSenderDisplayName(ConfigUtils.getConfigString(ConfigUtils.BATCH_FAILURE_ALERT_EMAIL_SENDER));
            email.setSubject(
                ConfigUtils.getConfigString(ConfigUtils.BATCH_FAILURE_ALERT_EMAIL_SUBJECT).replace('{{JOB}}', className)
            );
            email.setPlainTextBody(String.join(events, '\n'));
            Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{ email });
            BatchApexErrorEventTriggerHelper.emailSent = email;
        } catch (Exception ex) {
            SMELogger.logError(ex);
        }
    }
}
