const { AbstractJsonRepository } = require('../core/AbstractJsonRepository')

/**
 * CategoryNewsRepository
 *
 * Stores and retrieves articles for each category in a dedicated JSON file.
 */
class CategoryNewsRepository extends AbstractJsonRepository {
  constructor(dataDirectory) {
    super(dataDirectory)
  }

  /**
   * @param {import('../config/CategoryCatalog').NewsCategory} category
   * @returns {Promise<object>}
   */
  async readCategory(category) {
    return this.readJson(category.fileName, this._createEmptyDocument(category))
  }

  /**
   * @param {import('../config/CategoryCatalog').NewsCategory} category
   * @param {object[]} articles
   * @returns {Promise<object>}
   */
  async saveCategory(category, articles) {
    const document = {
      category: category.key,
      query: category.query,
      label: category.label,
      updatedAt: new Date().toISOString(),
      total: articles.length,
      articles
    }
    await this.writeJson(category.fileName, document)
    return document
  }

  /**
   * @param {import('../config/CategoryCatalog').NewsCategory} category
   * @returns {object}
   */
  _createEmptyDocument(category) {
    return {
      category: category.key,
      query: category.query,
      label: category.label,
      updatedAt: null,
      total: 0,
      articles: []
    }
  }
}

module.exports = {
  CategoryNewsRepository
}