const cron = require('node-cron')

/**
 * NewsRefreshScheduler
 *
 * Owns startup refresh and hourly refresh scheduling.
 */
class NewsRefreshScheduler {
  constructor(storageService, cronExpression, logger) {
    this._storageService = storageService
    this._cronExpression = cronExpression
    this._logger = logger
    this._task = null
  }

  /**
   * @returns {Promise<void>}
   */
  async start() {
    await this._runRefresh('startup')
    this._task = cron.schedule(this._cronExpression, async () => {
      await this._runRefresh('scheduled')
    })
  }

  /**
   * @returns {void}
   */
  stop() {
    if (this._task) {
      this._task.stop()
    }
  }

  /**
   * @param {string} trigger
   * @returns {Promise<void>}
   */
  async _runRefresh(trigger) {
    try {
      const results = await this._storageService.refreshAll()
      this._logger.info(`News refresh completed via ${trigger}`, { categories: results.length })
    } catch (error) {
      this._logger.error(`News refresh failed via ${trigger}`, error)
    }
  }
}

module.exports = {
  NewsRefreshScheduler
}