// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

// This script update the following source files:
// - /js/${arg0}/lib/version.ts
// - /js/node/script/install-metadata-versions.js (only for arg0=="node")
//
// version data is read from file /js/${arg0}/package.json

import fs from 'fs-extra';
import path from 'path';

const packageName = process.argv[2];
if (['common', 'web', 'node', 'react_native'].indexOf(packageName) === -1) {
  throw new Error('expect arg0 to be one of: common,web,node,react_native');
}

const PACKAGE_JSON_FILE = path.join(__dirname, '..', packageName, 'package.json');
const version = JSON.parse(fs.readFileSync(PACKAGE_JSON_FILE).toString()).version;

if (typeof version !== 'string') {
  throw new Error(`failed to parse "version" from file: ${PACKAGE_JSON_FILE}`);
}

{
  // update /js/${arg0}/lib/version.ts
  const FILE_CONTENT = `// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

// This file is generated by /js/scripts/update-version.ts
// Do not modify file content manually.

export const version = ${JSON.stringify(version)};
`;

  fs.writeFileSync(path.join(__dirname, '..', packageName, 'lib', 'version.ts'), FILE_CONTENT);
}

if (packageName === 'node') {
  // update /js/node/script/install-metadata-versions.js

  // If there is a second argument, use it as the version candidates. Otherwise, use the version from package.json.
  // ";" will be used as the separator.
  const versionCandidates = (process.argv[3] ?? '')
    .split(';')
    .map((v) => v.trim())
    .filter((v) => !!v);

  type NodeInstallMetadataVersions = Record<string, Array<{ feed: string; version: string }>>;
  const versions: NodeInstallMetadataVersions = { nuget: [] };

  if (versionCandidates.length > 0) {
    // append dev versions
    for (const v of versionCandidates) {
      versions.nuget.push({
        feed: 'nuget_nightly',
        version: v,
      });
    }
  } else {
    // append release version
    versions.nuget.push({
      feed: 'nuget',
      version,
    });
  }

  const FILE_CONTENT = `// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

// This file is generated by /js/scripts/update-version.ts
// Do not modify file content manually.

module.exports = ${JSON.stringify(versions)};
`;
  fs.writeFileSync(path.join(__dirname, '..', 'node', 'script', 'install-metadata-versions.js'), FILE_CONTENT);
}
