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

async function importChatTemplatesWithConfig(config) {
  const previousValue = process.env.CHAT_FUNNEL_CONFIG_JSON;

  try {
    process.env.CHAT_FUNNEL_CONFIG_JSON = JSON.stringify(config);
    return await import(new URL(`../src/chat-templates.js?case=${Date.now()}-${Math.random()}`, import.meta.url).href);
  } finally {
    if (previousValue === undefined) {
      delete process.env.CHAT_FUNNEL_CONFIG_JSON;
    } else {
      process.env.CHAT_FUNNEL_CONFIG_JSON = previousValue;
    }
  }
}

test("运行时配置支持跳过停用轮次并扩展到第5轮以后", async () => {
  const templates = await importChatTemplatesWithConfig({
    rounds: [
      { round: 1, name: "第1轮", templateText: "第一轮消息", passCondition: "条件1", enabled: true },
      { round: 2, name: "第2轮", templateText: "第二轮消息", passCondition: "条件2", enabled: false },
      { round: 3, name: "第3轮", templateText: "第三轮消息", passCondition: "条件3", enabled: true },
      { round: 4, name: "第4轮", templateText: "第四轮消息", passCondition: "条件4", enabled: true },
      { round: 5, name: "第5轮", templateText: "第五轮消息", passCondition: "条件5", enabled: true },
    ],
  });

  assert.equal(templates.TOTAL_ROUNDS, 4);
  assert.equal(templates.getMessageForRound(1, {}), "第一轮消息");
  assert.equal(templates.getMessageForRound(4, {}), "第五轮消息");
  assert.throws(() => templates.getMessageForRound(5, {}), /无效轮次/);
});

test("显式传入空轮次配置时不会回退到默认四轮", async () => {
  const templates = await importChatTemplatesWithConfig({ rounds: [] });

  assert.equal(templates.TOTAL_ROUNDS, 0);
  assert.throws(() => templates.getMessageForRound(1, {}), /无效轮次/);
});