// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: GPL-2.0-or-later

import assert from "node:assert/strict";
import test from "node:test";
import vm from "node:vm";
import { build } from "esbuild";

async function loadFormats() {
  const result = await build({
    entryPoints: [new URL("../src/core/format.ts", import.meta.url).pathname],
    bundle: true,
    format: "cjs",
    platform: "browser",
    target: "es2022",
    write: false,
  });
  const module = { exports: {} };
  vm.runInNewContext(result.outputFiles[0].text, { module, exports: module.exports });
  return module.exports;
}

test("frequency parsing respects explicit units and WFM shorthand", async () => {
  const { parseFrequencyInput } = await loadFormats();
  assert.equal(parseFrequencyInput("145.500 MHz", 1000, "FM"), 145_500_000);
  assert.equal(parseFrequencyInput("99.5", 100_000, "WFM"), 99_500_000);
  assert.equal(parseFrequencyInput("995", 100_000, "WFM"), 99_500_000);
  assert.equal(parseFrequencyInput("not a frequency", 1000, "USB"), null);
});

test("frequency and byte formatters handle display boundaries", async () => {
  const { formatByteSize, formatFrequencyForHumans, formatWavelength } = await loadFormats();
  assert.equal(formatFrequencyForHumans(145_500_000), "145.500 MHz");
  assert.equal(formatByteSize(1536), "1.5 KB");
  assert.equal(formatWavelength(299_792_458), "1 m");
});
