import { describe, expect, it } from "vitest";
import { buildQueryPlan } from "./QueryPlanPreview";
import type { DemandMap } from "../../domain/types";
import { isThreadsSearchable } from "../../lib/threadsTerm";

const map: DemandMap = {
  product_id: "p1", demand_input_version: "v1", map_version: 2, state: "ready",
  pain_phrases: [{ text: "漏水", kind: "pain", origin: "product", enabled: true }, { text: "壁癌", kind: "pain", origin: "product", enabled: true }],
  scenario_phrases: [{ text: "天花板滴水", kind: "scenario", origin: "product", basis_text: "產品情境", enabled: true }],
  desired_outcomes: [{ text: "找人處理", kind: "outcome", origin: "product", enabled: true }],
  solution_signals: [{ text: "抓漏", kind: "solution", origin: "product", enabled: true }],
  exclusion_signals: [{ text: "徵才", kind: "exclusion", origin: "product", enabled: true }],
  source_basis: ["安心抓漏"], custom_phrases: [], updated_at: 1,
};

describe("QueryPlanPreview", () => {
  it("generates at most six searchable groups and keeps exclusions", () => {
    const groups = buildQueryPlan(map);
    expect(groups.length).toBeGreaterThan(0);
    expect(groups.length).toBeLessThanOrEqual(6);
    expect(groups[0].exclusion).toEqual(["徵才"]);
    expect(groups.every((group) => {
      const query = group.terms.join(" ");
      return group.terms.length > 0 && group.terms.length <= 2 && isThreadsSearchable(query)
        && group.terms.every((term) => term !== "安心抓漏" && isThreadsSearchable(term));
    })).toBe(true);
  });

  it("falls back to scenario/outcome when the pain list is empty", () => {
    const groups = buildQueryPlan({ ...map, pain_phrases: [] });
    expect(groups.length).toBeGreaterThan(0);
    expect(groups.every((group) => isThreadsSearchable(group.terms.join(" ")))).toBe(true);
  });

  it("shortens long demand sentences into searchable queries", () => {
    const groups = buildQueryPlan({
      ...map,
      pain_phrases: [{ text: "晚上睡覺容易口乾舌燥怎麼辦", kind: "pain", origin: "product", enabled: true }],
      scenario_phrases: [{ text: "換季日常修護", kind: "scenario", origin: "product", enabled: true }],
    });
    expect(groups.length).toBeGreaterThan(0);
    expect(groups.every((group) => isThreadsSearchable(group.terms.join(" ")))).toBe(true);
    expect(groups.some((group) => group.terms.includes("口乾舌燥") || group.terms.includes("晚上睡覺"))).toBe(true);
  });
});
