import { JobQueue } from '@server/lib/job-queue/index.js'
import { LiveVideoModel, LiveVideoStatus } from '@server/models/video/live-video.js'
import { getLiveVideoStartJobId, LIVE_VIDEO_START_JOB_TYPE, LIVE_VIDEO_START_LEAD_TIME_MS } from './shared.js'

export async function syncLiveVideoStartJob (liveVideo: LiveVideoModel, options: {
  replace: boolean
}) {
  const jobId = getLiveVideoStartJobId(liveVideo.id)
  const existingJob = await JobQueue.Instance.getJob(LIVE_VIDEO_START_JOB_TYPE, jobId)

  if (existingJob) {
    const state = await existingJob.getState()

    if (options.replace && state === 'active') {
      return existingJob
    }

    if (!options.replace) {
      if (state !== 'completed' && state !== 'failed') return existingJob
    }

    await existingJob.remove()
  }

  if (liveVideo.status !== LiveVideoStatus.SCHEDULED) return undefined
  if (liveVideo.endTime.getTime() <= Date.now()) return undefined

  const delay = Math.max(0, liveVideo.startTime.getTime() - Date.now() - LIVE_VIDEO_START_LEAD_TIME_MS)

  return JobQueue.Instance.createJob({
    type: LIVE_VIDEO_START_JOB_TYPE,
    payload: { liveVideoId: liveVideo.id },
    delay,
    jobId
  })
}

export async function removeLiveVideoStartJob (liveVideoId: number) {
  const jobId = getLiveVideoStartJobId(liveVideoId)
  const existingJob = await JobQueue.Instance.getJob(LIVE_VIDEO_START_JOB_TYPE, jobId)
  if (!existingJob) return false

  const state = await existingJob.getState()
  if (state === 'active') return false

  await existingJob.remove()
  return true
}
