const fs = require('fs');
const packageMetadata = require('../package.json');

const constantsFilename = './src/app-version-constants.ts';
const { name, description, version, contributors } = packageMetadata;
const date = new Date().toISOString().split('T')[0];
const data = `/* eslint-disable */
// ----------------------------------------------------------------------------------------
// Do not edit this file, it is auto-generated by scripts/generate-version.js
// ----------------------------------------------------------------------------------------
export const APP_VERSION_INFO = Object.freeze({
  NAME: '${name}',
  DESCRIPTION: "${description}",
  VERSION: '${version}',
  VERSION_DATE: '${date}',
});

export const LONG_VERSION_DATE = '${version} (${date})';

export const CONTRIBUTORS = Object.freeze(${JSON.stringify(contributors)});
`;

const generateMarkdownConst = () => {
  const markdownContent = fs.readFileSync('CHANGELOG.md', { encoding: 'utf8' });
  const backTick = '`';
  return `export const CHANGELOG_MD: string = ${backTick}${markdownContent}${backTick};\n`;
};

const main = () => {
  console.info('\t[Version generator script]');

  try {
    console.info(`\t- writing file "${constantsFilename}"...`, packageMetadata.version);

    const changeLogConst = generateMarkdownConst();
    const dataWithMarkdown = `${data}${changeLogConst}`;
    fs.writeFileSync(constantsFilename, dataWithMarkdown, { encoding: 'utf8' });

    console.info(`\t- file "${constantsFilename}" written successfully.`);
  } catch (err) {
    console.error(`\t- error while writing file "${constantsFilename}": ${err.message}`, err);
  }
};

main();
