const path = require('path')

/**
 * ServiceConfig
 *
 * Centralizes environment parsing and default values.
 */
class ServiceConfig {
  constructor(env = process.env) {
    this._env = env
  }

  /**
   * @returns {{port: number, pageSize: number, refreshCron: string, dataDirectory: string, pinnedArticleUrls: string[], pinnedCategoryKeys: string[] | null, pinnedTtlMs: number}}
   */
  toRuntimeConfig() {
    return {
      port: Number(this._env.PORT || 3100),
      pageSize: Number(this._env.NEWS_PAGE_SIZE || 20),
      refreshCron: this._env.NEWS_REFRESH_CRON || '0 * * * *',
      dataDirectory: path.resolve(process.cwd(), this._env.DATA_DIR || './data'),
      pinnedArticleUrls: this._parseList(this._env.NEWS_PINNED_ARTICLE_URLS, [
        'https://n.news.naver.com/mnews/article/009/0005689327'
      ]),
      pinnedCategoryKeys: this._parseList(this._env.NEWS_PINNED_CATEGORIES, null),
      pinnedTtlMs: Number(this._env.NEWS_PINNED_TTL_MS || 6 * 60 * 60 * 1000)
    }
  }

  /**
   * Parses a comma-separated environment value into a trimmed list.
   *
   * @param {string | undefined} value
   * @param {string[] | null} fallback - Returned when the value is unset.
   * @returns {string[] | null}
   */
  _parseList(value, fallback) {
    if (value === undefined || value === null || value.trim() === '') {
      return fallback
    }
    return value
      .split(',')
      .map((item) => item.trim())
      .filter(Boolean)
  }
}

module.exports = {
  ServiceConfig
}
