import { readFileSync } from 'fs';
import { join } from 'path';
import { parse } from 'jsonc-parser';
import { MainConfigModel } from '../models/main-config-model';

let data: MainConfigModel | null = null;

export default (): MainConfigModel => {
  if (data) {
    return data;
  }

  const userDefinedConfigPath =
    process.env['REDMINE_ISSUE_EVENT_EMITTER_CONFIG_PATH'];
  const defaultConfigPath = join('configs', 'issue-event-emitter-config.jsonc');
  const configPath = userDefinedConfigPath || defaultConfigPath;

  const rawData = readFileSync(configPath, {
    encoding: 'utf-8',
  });

  data = parse(rawData);
  return data;
};
