const fs = require('fs');
const path = require('path');

const root = process.cwd();
const packageJsonPath = path.join(root, 'package.json');
const ngswConfigPath = path.join(root, 'ngsw-config.json');

const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
const ngswConfig = JSON.parse(fs.readFileSync(ngswConfigPath, 'utf8'));

const now = new Date();
const buildDate = process.env.BUILD_DATE || now.toISOString();
const previousAppVersion = ngswConfig.appData?.appVersion || packageJson.version || '0.0.0';
const appVersion =
  process.env.APP_VERSION ||
  previousAppVersion.replace(
    /^(\d+)\.(\d+)\.(\d+)$/,
    (_, major, minor, patch) => `${major}.${minor}.${Number(patch) + 1}`,
  );
const previousBuildNumber = Number(ngswConfig.appData?.buildNumber || 0);
const buildNumber = Number(process.env.BUILD_NUMBER || previousBuildNumber + 1);

ngswConfig.appData = {
  ...(ngswConfig.appData || {}),
  appVersion,
  buildNumber,
  buildDate,
};

fs.writeFileSync(ngswConfigPath, `${JSON.stringify(ngswConfig, null, 2)}\n`);
