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

import {
  buildTemplateCreateRequest,
  EMPTY_TEMPLATE_DRAFT,
  isTemplateDraftValid,
  type TemplateDraft,
} from "./templates";

const draft = (over: Partial<TemplateDraft>): TemplateDraft => ({
  ...EMPTY_TEMPLATE_DRAFT,
  ...over,
});

describe("isTemplateDraftValid", () => {
  it("returns true when title and body are both non-empty", () => {
    expect(isTemplateDraftValid(draft({ title: "标题", body: "正文" }))).toBe(
      true,
    );
  });

  it("returns false when title is blank", () => {
    expect(isTemplateDraftValid(draft({ title: "  ", body: "正文" }))).toBe(
      false,
    );
  });

  it("returns false when body is blank", () => {
    expect(isTemplateDraftValid(draft({ title: "标题", body: "" }))).toBe(false);
  });

  it("returns false for the empty draft", () => {
    expect(isTemplateDraftValid(EMPTY_TEMPLATE_DRAFT)).toBe(false);
  });
});

describe("buildTemplateCreateRequest", () => {
  it("trims title and body and includes optional fields", () => {
    const body = buildTemplateCreateRequest(
      draft({
        title: "  脑洞模板  ",
        body: "  写一个穿越故事  ",
        category: " 脑洞 ",
        toolKey: " idea ",
      }),
    );
    expect(body).toEqual({
      title: "脑洞模板",
      body: "写一个穿越故事",
      category: "脑洞",
      tool_key: "idea",
    });
  });

  it("nulls out blank category and tool_key", () => {
    const body = buildTemplateCreateRequest(
      draft({ title: "t", body: "b", category: "  ", toolKey: "" }),
    );
    expect(body.category).toBeNull();
    expect(body.tool_key).toBeNull();
  });
});
