const assert = require('assert/strict');
const fs = require('fs');
const vm = require('vm');

const cases = [
  [
    'https://172.19.153.70:62066/twirp/path?sig=a%2Bb%3D&expires=2026-07-22+21%253A28',
    'http://172.19.153.70:62066/twirp/path?sig=a%2Bb%3D&expires=2026-07-22+21%253A28'
  ],
  ['http://172.19.153.70:62066/twirp/path?sig=a%2Bb%3D', 'http://172.19.153.70:62066/twirp/path?sig=a%2Bb%3D'],
  ['https://172.18.4.8:62066/twirp/path', 'https://172.18.4.8:62066/twirp/path'],
  ['https://172.20.4.8:62066/twirp/path', 'https://172.20.4.8:62066/twirp/path'],
  ['https://172.31.4.8:62066/twirp/path', 'https://172.31.4.8:62066/twirp/path'],
  ['https://git.data-it.tech/api/v1', 'https://git.data-it.tech/api/v1']
];

for (const file of ['upload/dist/index.js', 'download/dist/index.js']) {
  const source = fs.readFileSync(file, 'utf8');
  const begin = source.indexOf('function getResultsServiceUrl()');
  const end = source.indexOf('function isGhes()', begin);
  assert.ok(begin >= 0 && end >= 0, `${file}: helper segment not found`);
  const context = {process: {env: {}}, URL, exports: {}};
  vm.runInNewContext(source.slice(begin, end), context);
  for (const [input, expected] of cases) {
    assert.equal(context.exports.normalizeDockerBridgeUrl(input), expected, `${file}: ${input}`);
  }
  context.process.env.ACTIONS_RESULTS_URL = cases[0][0];
  assert.equal(context.exports.getResultsServiceUrl(), 'http://172.19.153.70:62066', `${file}: results service origin`);
}

const upload = fs.readFileSync('upload/dist/index.js', 'utf8');
const download = fs.readFileSync('download/dist/index.js', 'utf8');
assert.ok(upload.includes('new storage_blob_1.BlobClient((0, config_1.normalizeDockerBridgeUrl)(authenticatedUploadURL))'));
assert.ok(download.includes('yield streamExtract((0, config_1.normalizeDockerBridgeUrl)(signedUrl), downloadPath);'));

console.log('internal results service address checks passed');
