import { logger, loggerTagsFactory } from '@server/helpers/logger.js'
import { SCHEDULER_INTERVALS_MS } from '@server/initializers/constants.js'
import { syncLiveVideoStartJob } from '@server/lib/live-videos/live-video-jobs.js'
import { LIVE_VIDEO_START_LEAD_TIME_MS } from '@server/lib/live-videos/shared.js'
import { LiveVideoModel } from '@server/models/video/live-video.js'
import { AbstractScheduler } from './abstract-scheduler.js'

const lTags = loggerTagsFactory('schedulers', 'live-video-start')
const RECOVERY_WINDOW_MS = 5 * 60 * 1000

export class LiveVideoStartScheduler extends AbstractScheduler {
  private static instance: AbstractScheduler

  protected schedulerIntervalMs = SCHEDULER_INTERVALS_MS.LIVE_VIDEO_START

  private constructor () {
    super({ randomRunOnEnable: false })
  }

  protected async internalExecute () {
    logger.debug('Running live video start scheduler', lTags())

    const now = Date.now()
    const liveVideos = await LiveVideoModel.listForStarting({
      startBefore: new Date(now + RECOVERY_WINDOW_MS + LIVE_VIDEO_START_LEAD_TIME_MS),
      endAfter: new Date(now)
    })
    
    for (const liveVideo of liveVideos) {
      await syncLiveVideoStartJob(liveVideo, { replace: false })
    }
  }

  static get Instance () {
    return this.instance || (this.instance = new this())
  }
}
