/***********************************************************************************************************
 * Name         : TempFormResponseBatchReprocess
 * Purpose      : Job to process TempFormResponse records which previuosly failed to be processed
 **********************************************************************************************************/

public without sharing class TempFormResponseBatchReprocess implements Database.Batchable<SObject>, Database.RaisesPlatformEvents, Schedulable {
    @TestVisible
    private String query;

    public TempFormResponseBatchReprocess(String query) {
        this.query = query;
    }

    public Database.queryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator(query);
    }

    public void execute(Database.BatchableContext bc, List<Temp_Form_Response__c> tempFormResponses) {
        List<Form_Response__c> formResponsesToInsert = new List<Form_Response__c>();

        for (Temp_Form_Response__c tfr : tempFormResponses) {
            formResponsesToInsert.add(TempFormResponseBatchUtils.mapTempFormResponseToFormResponse(tfr));
        }

        insert formResponsesToInsert;
        delete tempFormResponses;
    }

    public void finish(Database.BatchableContext bc) {
    }

    public void execute(SchedulableContext sc) {
        Database.executeBatch(
            new TempFormResponseBatchReprocess(TempFormResponseBatchUtils.query.replace('<', '>=')),
            ConfigUtils.getConfigInt(ConfigUtils.TFR_RETRY_JOB_BATCH_SIZE)
        );
    }

    public static void schedule() {
        BatchJobUtils.scheduleJob(
            new TempFormResponseBatchReprocess(null),
            ConfigUtils.getConfigString(ConfigUtils.TFR_RETRY_JOB_CRON_EXPS)
        );
    }
}
