import { describe, expect, it } from "vitest";

import {
  renderPromptPayloadStrings,
  renderPromptTemplate,
  resolvePromptDefinition,
  resolvePromptStoreRuntimeConfig,
} from "./prompt-runtime.js";

describe("resolvePromptStoreRuntimeConfig", () => {
  it("reads dedicated prompt store env vars", () => {
    const config = resolvePromptStoreRuntimeConfig({
      PROMPT_SUPABASE_URL: "https://prompt.example.supabase.co",
      PROMPT_SUPABASE_SERVICE_ROLE_KEY: "service-role-key",
      PROMPT_ENV: "staging",
      PROMPT_CACHE_TTL_MS: "12345",
    } as NodeJS.ProcessEnv);

    expect(config).toEqual({
      url: "https://prompt.example.supabase.co",
      key: "service-role-key",
      targetEnv: "staging",
      cacheTtlMs: 12345,
      enabled: true,
    });
  });
});

describe("renderPromptTemplate", () => {
  it("replaces handlebars style variables", () => {
    expect(renderPromptTemplate("你好，{{ name }}，数量={{count}}", {
      name: "钢化玻璃",
      count: 3,
    })).toBe("你好，钢化玻璃，数量=3");
  });

  it("leaves missing variables as empty string", () => {
    expect(renderPromptTemplate("{{a}}-{{b}}", { a: "ok" })).toBe("ok-");
  });
});

describe("renderPromptPayloadStrings", () => {
  it("renders nested objects and arrays", () => {
    const rendered = renderPromptPayloadStrings({
      system: "系统：{{name}}",
      nested: {
        lines: ["A={{value}}", "B={{name}}"],
      },
    }, {
      name: "商品A",
      value: 12,
    });

    expect(rendered).toEqual({
      system: "系统：商品A",
      nested: {
        lines: ["A=12", "B=商品A"],
      },
    });
  });
});

describe("resolvePromptDefinition", () => {
  it("throws when prompt store env vars are missing", async () => {
    await expect(resolvePromptDefinition("automation.search.page_review.bundle", {
      env: {} as NodeJS.ProcessEnv,
    })).rejects.toThrow(/PROMPT_SUPABASE_URL|PROMPT_SUPABASE_SERVICE_ROLE_KEY/);
  });
});