import type {
  ExecutionContext,
  D1Database,
  DurableObjectNamespace,
} from '@cloudflare/workers-types'
import { CacheCreator } from './src/jobs/cache-creator'
import { createApp } from './src/app'
import { ensureWorkerInit } from './src/lib/worker-init'
import { runFlashDeliveryToggleCron } from './src/lib/flash-delivery-cron'
import {
  handleNotifQueue,
  handleOrderPlacedQueue,
  handleOrderCancelledQueue,
} from './src/lib/queue-consumer'

export { CacheCreator }

let app: ReturnType<typeof createApp> | null = null

export default {
  async fetch(
    request: Request,
    env: Record<string, string> & {
      DB?: D1Database
      CACHE_CREATOR: DurableObjectNamespace
      NOTIF_QUEUE: {
        send: (message: unknown) => Promise<void>
      }
      ORDER_PLACED_QUEUE: {
        send: (message: unknown) => Promise<void>
      }
      ORDER_CANCELLED_QUEUE: {
        send: (message: unknown) => Promise<void>
      }
    },
    ctx: ExecutionContext
  ) {
    ensureWorkerInit(env)
    if (!app) {
      app = createApp()
    }
    return app.fetch(request, env, ctx)
  },
  async queue(
    batch: any,
    env: Record<string, string> & {
      NOTIF_QUEUE: {
        send: (message: unknown) => Promise<void>
      }
      ORDER_PLACED_QUEUE: {
        send: (message: unknown) => Promise<void>
      }
      ORDER_CANCELLED_QUEUE: {
        send: (message: unknown) => Promise<void>
      }
      DB?: D1Database
      NOTIF_QUEUE_NAME: string
      ORDER_PLACED_QUEUE_NAME: string
      ORDER_CANCELLED_QUEUE_NAME: string
    }
  ) {
    ensureWorkerInit(env)
    console.log('from the queue handler')
    if (batch?.queue === env.NOTIF_QUEUE_NAME) {
      await handleNotifQueue(batch)
      return
    }

    if (batch?.queue === env.ORDER_PLACED_QUEUE_NAME) {
      await handleOrderPlacedQueue(batch)
      return
    }

    if (batch?.queue === env.ORDER_CANCELLED_QUEUE_NAME) {
      await handleOrderCancelledQueue(batch)
      return
    }

    handleNotifQueue(batch)
  },
  async scheduled(
    event: any,
    env: Record<string, string> & {
      DB?: D1Database
    },
    ctx: ExecutionContext
  ) {
    console.log('from the cron trigger first func');
    await runFlashDeliveryToggleCron({cron: event.cron, env});
    // ctx.waitUntil(runFlashDeliveryToggleCron({ cron: event.cron, env }))
  },
}
