// 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 { createHost } from "./host-fixture.mjs";
import { bundleEntry } from "./bundle-entry.mjs";

test("background decode loads configuration for the explicitly selected rig", async () => {
  const requested = [];
  const window = {
    ...createHost(),
    decoderRegistry: [],
    trxUi: { confirm: async () => true },
  };
  const context = vm.createContext({
    window,
    document: { getElementById: () => null },
    fetch: async (url) => {
      requested.push(url);
      return {
        ok: true,
        json: async () => url === "/bookmarks"
          ? []
          : url.endsWith("/status")
            ? { entries: [] }
            : { remote: "rig/a", enabled: false, bookmark_ids: [] },
      };
    },
    setInterval: () => 1,
    clearInterval() {},
    setTimeout,
    URL,
    Set,
    Error,
    console,
  });
  const source = await bundleEntry(new URL("../src/plugins/background-decode.ts", import.meta.url));
  new vm.Script(source).runInContext(context);

  window.trx.modules.backgroundDecode.initialize("rig/a", "control");
  await new Promise((resolve) => setTimeout(resolve, 0));
  assert.ok(requested.includes("/background-decode/rig%2Fa"));
  assert.ok(requested.includes("/bookmarks"));
  assert.ok(requested.includes("/background-decode/rig%2Fa/status"));
  assert.equal(window.initBackgroundDecode, undefined);
});
