/***********************************************************************************************************
 * Name         : FutureDatePickerBatch
 * Purpose      : Creates the Future Date Picker report and sends it via email to specific recipients
 **********************************************************************************************************/

public with sharing class FutureDatePickerBatch implements Database.Batchable<sObject>, Database.Stateful, Schedulable, Database.RaisesPlatformEvents {
    List<String> csvFile = new List<String>{ 'Migration ID,Form Tool Name' };
    Integer totalDeletedRecords = 0;

    public Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator(
            [
                SELECT Id, Value__c
                FROM BatchReportLine__c
                WHERE Category__c = :ConfigUtils.getConfigString(ConfigUtils.BRL_CATEGORY_FUTURE_BIRTHDATE)
            ]
        );
    }

    public void execute(Database.BatchableContext context, List<BatchReportLine__c> reportLines) {
        for (BatchReportLine__c reportLine :reportLines) {
            csvFile.add(reportLine.Value__c);
        }
        Database.delete(reportLines, false);
    }

    public void finish(Database.BatchableContext context) {
        Integer recordsAmount = csvFile.size() - 1;

        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(ConfigUtils.getConfigMultipleStrings(ConfigUtils.FUTURE_DATE_RECIPIENTS));
        email.setSenderDisplayName(ConfigUtils.getConfigString(ConfigUtils.FUTURE_DATE_SENDER));

        String subject = recordsAmount >= ConfigUtils.getConfigInt(ConfigUtils.FUTURE_DATE_ALERT_THRESHOLD)
            ? 'Attention-High Count!! Future Date Picker Fans'
            : 'Future Date Picker Fans';

        email.setSubject(subject);

        String body = recordsAmount.format() + ' Fan record(s) have been updated.';
        email.setPlainTextBody(body);

        if (recordsAmount > 0) {
            Messaging.EmailFileAttachment csvAttachment = new Messaging.EmailFileAttachment();
            Blob csvBlob = Blob.valueOf(String.join(csvFile, '\n'));
            csvAttachment.setFileName('UpdatedFans.csv');
            csvAttachment.setBody(csvBlob);
            email.setFileAttachments(new List<Messaging.EmailFileAttachment>{ csvAttachment });
        }

        Messaging.sendEmail(new List<Messaging.Email>{ email });
    }

    public void execute(SchedulableContext sc) {
        Database.executeBatch(new FutureDatePickerBatch());
    }

    public static void schedule() {
        BatchJobUtils.scheduleJob(
            new FutureDatePickerBatch(),
            ConfigUtils.getConfigString(ConfigUtils.FUTURE_BIRTHDATE_CRON_EXP)
        );
    }
}