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

import type { RuleView } from "@/lib/api/types";
import {
  buildRuleCreateRequest,
  groupByLevel,
  hasUsableContent,
  isRuleLevel,
  RULE_LEVELS,
} from "./rules";

describe("isRuleLevel", () => {
  it("accepts the four known levels only", () => {
    for (const lv of RULE_LEVELS) expect(isRuleLevel(lv)).toBe(true);
    expect(isRuleLevel("bogus")).toBe(false);
  });
});

describe("groupByLevel", () => {
  it("groups rules by level, unknown level falls to project", () => {
    const rules: RuleView[] = [
      { id: "r1", level: "global", content: "g1" },
      { id: "r2", level: "project", content: "p1" },
      { id: "r3", level: "weird", content: "x1" },
    ];
    const groups = groupByLevel(rules);
    expect(groups.global).toEqual([{ id: "r1", level: "global", content: "g1" }]);
    expect(groups.project).toEqual([
      { id: "r2", level: "project", content: "p1" },
      { id: "r3", level: "weird", content: "x1" },
    ]);
    expect(groups.genre).toEqual([]);
  });

  it("handles undefined", () => {
    expect(groupByLevel(undefined).style).toEqual([]);
  });
});

describe("buildRuleCreateRequest", () => {
  it("trims content", () => {
    expect(buildRuleCreateRequest("project", "  禁现代词  ")).toEqual({
      level: "project",
      content: "禁现代词",
    });
  });
});

describe("hasUsableContent", () => {
  it("true only when non-blank", () => {
    expect(hasUsableContent("  ")).toBe(false);
    expect(hasUsableContent(" x ")).toBe(true);
  });
});
