import { beforeEach, describe, expect, it, vi } from "vitest";
import { importFreshModule } from "../../test/helpers/import-fresh.ts";

describe("bundled channel config runtime", () => {
  beforeEach(() => {
    vi.doUnmock("../channels/plugins/bundled.js");
  });

  it("tolerates an unavailable bundled channel list during import", async () => {
    vi.doMock("../channels/plugins/bundled.js", () => ({
      listBundledChannelPlugins: () => undefined,
    }));

    const runtimeModule = await importFreshModule<
      typeof import("./bundled-channel-config-runtime.js")
    >(import.meta.url, "./bundled-channel-config-runtime.js?scope=missing-bundled-list");

    expect(runtimeModule.getBundledChannelConfigSchemaMap().get("msteams")).toBeDefined();
    expect(runtimeModule.getBundledChannelRuntimeMap().get("msteams")).toBeDefined();
  });

  it("falls back to static channel schemas when bundled plugin access hits a TDZ-style ReferenceError", async () => {
    vi.doMock("../channels/plugins/bundled.js", () => {
      return {
        listBundledChannelPlugins() {
          throw new ReferenceError("Cannot access 'bundledChannelPlugins' before initialization.");
        },
      };
    });

    const runtime = await importFreshModule<typeof import("./bundled-channel-config-runtime.js")>(
      import.meta.url,
      "./bundled-channel-config-runtime.js?scope=tdz-reference-error",
    );
    const configSchemaMap = runtime.getBundledChannelConfigSchemaMap();

    expect(configSchemaMap.has("msteams")).toBe(true);
    expect(configSchemaMap.has("whatsapp")).toBe(true);
  });
});
