import { Cron } from 'croner'
import type { CronJob } from './schedules'
import { executeJob } from './executor'

const scheduled = new Map<string, Cron>()

export function scheduleJob(job: CronJob, onUpdate: () => void) {
  // Stop existing if any
  scheduled.get(job.id)?.stop()

  const cron = new Cron(job.cronExpr, async () => {
    await executeJob(job, onUpdate)
  })

  scheduled.set(job.id, cron)
  job.nextRun = cron.nextRun()?.getTime()
}

export function stopJob(jobId: string) {
  scheduled.get(jobId)?.stop()
  scheduled.delete(jobId)
}

export function getNextRun(jobId: string): number | undefined {
  return scheduled.get(jobId)?.nextRun()?.getTime()
}
