import { createInvoice, sendInvoices } from '@apps/finance/services/invoices'
import Queue from '@core/objects/queue'

const exportInvoices = async(req, job) => {

  const { invoice_ids } = job.data

  const index = job.data.index || 0

  if(index < invoice_ids.length) {

    await createInvoice(req, {
      id: invoice_ids[index]
    })

    await ExportInvoicesQueue.enqueue(req, {
      ...job.data,
      index: index + 1
    })

  } else {

    await sendInvoices(req, job.data)

  }

}

const ExportInvoicesQueue = new Queue({
  queue: 'maha:worker',
  name: 'export_invoices',
  processor: exportInvoices
})

export default ExportInvoicesQueue
