import assert from "node:assert/strict";
import test from "node:test";

async function withEnv(patch, fn) {
  const previous = {};
  for (const key of Object.keys(patch)) {
    previous[key] = process.env[key];
    if (patch[key] === undefined) {
      delete process.env[key];
    } else {
      process.env[key] = patch[key];
    }
  }

  try {
    return await fn();
  } finally {
    for (const [key, value] of Object.entries(previous)) {
      if (value === undefined) {
        delete process.env[key];
      } else {
        process.env[key] = value;
      }
    }
  }
}

test("client proxy range defaults to the single configured proxy port", async () => {
  await withEnv(
    {
      PROXY_PORT: "8082",
      CLIENT_PROXY_PORT_START: "8082",
      CLIENT_PROXY_PORT_END: undefined,
    },
    async () => {
      const { settings } = await import(
        `../../src/server/config.js?single-proxy-port=${Date.now()}`
      );

      assert.equal(settings.proxyPort, 8082);
      assert.equal(settings.clientProxyPortStart, 8082);
      assert.equal(settings.clientProxyPortEnd, 8082);
    },
  );
});
