const { logger } = require('../utils');
const { Performance } = require('../models');
const { sendChallengeListEmail, createEmptyResults } = require('./utils');

module.exports = () => {
  logger.jobsLog('Email Challenge List Check');
  return Performance.findForListExporting()
    .then(([performance]) => {
      if (!performance) {
        logger.jobsLog('Email Challenge List Check: no email to send');
        return;
      }

      Promise.all([
        sendChallengeListEmail.sendChallengeListEmail(performance.id),
        createEmptyResults(performance.id),
        Performance.update({
          id: performance.id,
          list_exported: true
        })
      ])
        .then(() => {
          logger.jobsLog('Email Challenge List Check: done!');
        })
        .catch((err) => {
          logger.errorLog('Email Challenge List Check', err);
        });
    });
};

@@ -159,57 +159,78 @@
 );%0A%0A
-module.exports
+const helper
  = (
+id
 ) =%3E
- %7B%0A  logger.jobsLog('Email 
+%0A  Promise.all(%5B%0A    sendChallengeListEmail.send
 Chal
@@ -238,126 +238,142 @@
 enge
- 
 List
- Check');%0A  return Performance.findForListE
+Email(id),%0A    createEmptyResults(id),%0A    Performance.update(%7B%0A      id,%0A      list_e
 xport
-ing()%0A    .then((%5Bperformance%5D) =%3E %7B%0A      if (!performance) %7B%0A  
+ed: true%0A    %7D)%0A  %5D)%0A    .then(() =%3E %7B%0A
     
@@ -422,32 +422,21 @@
 ck: 
-no email to send
+done!
 ');%0A    
     
@@ -435,84 +435,162 @@
     
+%7D)%0A
     
-return;%0A      %7D%0A%0A      Promise.all(%5B%0A        sendChallengeListEmail.send
+.catch((err) =%3E %7B%0A      logger.errorLog('Email Challenge List Check', err);%0A    %7D);%0A%0Amodule.exports = (performanceId) =%3E %7B%0A  logger.jobsLog('Email 
 Chal
@@ -594,25 +594,37 @@
 hallenge
+ 
 List
-Email
+ Check');%0A%0A  if 
 (perform
@@ -631,40 +631,31 @@
 ance
-.id),%0A    
+Id) %7B%0A
     
-c
 re
-ateEmptyResults
+turn helper
 (per
@@ -666,304 +666,284 @@
 ance
-.id),%0A        Performance.update(%7B%0A          id: performance.id,%0A          list_exported: true%0A        %7D)%0A      %5D)%0A        .then(() =%3E %7B%0A          logger.jobsLog('Email Challenge List Check: done!');%0A        %7D)%0A        .catch((err) =%3E %7B%0A          logger.errorLog('Email Challenge List Check', err
+Id);%0A  %7D else %7B%0A    return Performance.findForListExporting()%0A      .then((%5Bperformance%5D) =%3E %7B%0A        if (performance) %7B%0A          return helper(performance.id);%0A        %7D%0A        logger.jobsLog('Email Challenge List Check: no email to send');%0A        return Promise.resolve(
 );%0A 
@@ -951,21 +951,15 @@
     
-  
 %7D);%0A  
-  %7D);
+%7D
 %0A%7D;%0A

make email challenge list job take an optional id