import dayjs from 'dayjs'
import { initializeAllStores } from '@/src/stores/store-initializer'
import { ensureWorkerInit } from '@/src/lib/worker-init'

const LAST_TRIGGER_KEY = 'lastTrigger'
const ALARM_DELAY_MINUTES = 0.5
// const ALARM_DELAY_MINUTES = 0.1

export class CacheCreator {
  private state: any
  private env: any

  constructor(state: any, env: any) {
    this.state = state
    this.env = env
    ensureWorkerInit(env)
  }

  async schedule(): Promise<void> {
    console.log( 'from the fetch method of durable object')
    // if (request.method === 'POST' && url.pathname === '/schedule') {
      const now = Date.now()
      await this.state.storage.put(LAST_TRIGGER_KEY, now)
      const alarmAt = dayjs(now).add(ALARM_DELAY_MINUTES, 'minute').valueOf()
      await this.state.storage.setAlarm(alarmAt)
      // return new Response('OK')
    // }
    // if (request.method === 'POST' && url.pathname === '/clear') {
      await this.state.storage.deleteAll()
      // return new Response('OK')
    // }

    // return new Response('CacheCreator ready', { status: 200 })
  }


  async fetch(request: Request): Promise<Response> {
    const url = new URL(request.url)
    if (request.method === 'POST' && url.pathname === '/schedule') {
      const now = Date.now()
      await this.state.storage.put(LAST_TRIGGER_KEY, now)
      const alarmAt = dayjs(now).add(ALARM_DELAY_MINUTES, 'minute').valueOf()
      await this.state.storage.setAlarm(alarmAt)
      return new Response('OK')
    }
    if (request.method === 'POST' && url.pathname === '/clear') {
      await this.state.storage.deleteAll()
      return new Response('OK')
    }

    return new Response('CacheCreator ready', { status: 200 })
  }

  async alarm(): Promise<void> {
    ensureWorkerInit(this.env)
    console.log('from the shceduler')
    const lastTrigger = await this.state.storage.get(LAST_TRIGGER_KEY)
    if (!lastTrigger) {
      return
    }

    const threshold = dayjs().subtract(ALARM_DELAY_MINUTES, 'minute')
    const isQualify = dayjs(lastTrigger).isBefore(threshold); 
    console.log({isQualify, threshold, curr: dayjs(lastTrigger)})
    if (isQualify) {
      await initializeAllStores()
    }
  }
}
