// newsroom/job/update-feed.js
// Copyright (C) 2022 DTP Technologies, LLC
// License: Apache-2.0

'use strict';

const path = require('path');

const { SiteWorkerProcess } = require(path.join(__dirname, '..', '..', '..', '..', 'lib', 'site-lib'));

class UpdateFeedJob extends SiteWorkerProcess {

  static get COMPONENT ( ) {
    return {
      name: 'newsroomUpdateFeedJob',
      slug: 'newsroom-update-feed-job',
    };
  }

  constructor (worker) {
    super(worker, UpdateFeedJob.COMPONENT);
  }

  async start ( ) {
    await super.start();

    this.queue = await this.getJobQueue('newsroom', this.dtp.config.jobQueues.newsroom);

    this.log.info('registering job processor', { queue: this.queue.name, name: 'update-feed' });
    this.queue.process('update-feed', this.processUpdateFeed.bind(this));
  }

  async stop ( ) {
    await super.stop();
  }

  async processUpdateFeed (job) {
    const { feed: feedService } = this.dtp.services;
    const { feedId } = job.data;
    this.log.info('newsroom feed update job received', { id: job.id, feedId });

    try {
      const feed = await feedService.getById(feedId);
      await this.worker.updateFeed(feed);
    } catch (error) {
      this.log.error('failed to update newsroom feed', { feedId, error });
      throw error;
    }
  }
}

module.exports = UpdateFeedJob;