/***********************************************************************************************************
 * Name         : TempFormResponseBatch
 * Purpose      : Job to process TempFormResponse records
 **********************************************************************************************************/

public with sharing class TempFormResponseBatch implements Database.Batchable<SObject>, Database.RaisesPlatformEvents, Database.Stateful {
    @TestVisible
    private String query = TempFormResponseBatchUtils.query;

    Boolean isAnotherJobInstanceRunning = false;

    public Database.queryLocator start(Database.BatchableContext bc) {
        isAnotherJobInstanceRunning = TempFormResponseBatchUtils.isAnotherJobInstanceRunning(
            bc.getJobId(),
            'TempFormResponseBatch'
        );
        if (isAnotherJobInstanceRunning) {
            query = TempFormResponseBatchUtils.emptyQuery;
        }

        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) {
        Boolean shouldKeepRunning = ConfigUtils.getConfigBoolean(ConfigUtils.TFR_JOB_KEEP_RUNNING);
        if (!Test.isRunningTest() && !isAnotherJobInstanceRunning && shouldKeepRunning) {
            Id jobId = Database.executeBatch(
                new TempFormResponseBatch(),
                ConfigUtils.getConfigInt(ConfigUtils.TFR_JOB_BATCH_SIZE)
            );
            try {
                FlexQueue.moveJobToFront(jobId);
            } catch (Exception ex) {
            }
        }
    }
}
