import { toggleKeyVal } from '@/src/dbService'
import { CONST_KEYS } from '@/src/lib/const-keys'
import { computeConstants } from '@/src/lib/const-store'
import { ensureWorkerInit } from '@/src/lib/worker-init'


const CRON_TURN_OFF_FLASH_DELIVERY = '0 16 * * *' // 9:30 PM IST
const CRON_TURN_ON_FLASH_DELIVERY = '0 1 * * *' // 6:30 PM IST

export async function runFlashDeliveryToggleCron(params: {
  cron: string
  env: any
}) {
  console.log('from the cron job top level')
  const { cron, env } = params

  // Ensure DB bindings are initialized for this worker invocation
  ensureWorkerInit(env)

  if (cron !== CRON_TURN_OFF_FLASH_DELIVERY && cron !== CRON_TURN_ON_FLASH_DELIVERY) {
    console.log('flash delivery cron: ignoring unknown cron', cron)
    return
  }

  const enabled = cron === CRON_TURN_ON_FLASH_DELIVERY
  console.log('flash delivery cron: toggling isFlashDeliveryEnabled', { cron, enabled })

  await toggleKeyVal(CONST_KEYS.isFlashDeliveryEnabled, enabled)
  await computeConstants()
}
