import type { PressZoneBindings, QueueBinding } from './config.js'
import type { QueueJob } from './cron.js'

export interface ExecutionContextLike {
  waitUntil(promise: Promise<unknown>): void
}

export interface QueueMessageLike<T = unknown> {
  body: T
}

export interface QueueBatchLike<T = unknown> {
  messages: Array<QueueMessageLike<T>>
  queue?: QueueBinding<T>
}

async function handleJob(job: QueueJob): Promise<void> {
  switch (job.type) {
    case 'period-rollover-housekeeping':
    case 'reconcile-charge-intents':
      return
    default: {
      const exhaustive: never = job
      throw new Error(`Unsupported queue job: ${JSON.stringify(exhaustive)}`)
    }
  }
}

export async function consumeQueue(
  batch: QueueBatchLike<QueueJob>,
  _env: PressZoneBindings,
  context: ExecutionContextLike,
): Promise<void> {
  const work = Promise.all(batch.messages.map((message) => handleJob(message.body)))
  context.waitUntil(work)
  await work
}
