import { describe, expect, test } from "bun:test";
import {
  defaultChecked,
  groupFollowUps,
  type FollowUpRule,
} from "./fristenrechner-result";

// Pure helpers exercised here; the DOM-driven render path is covered
// by the live page test path (S2 is mount-on-deep-link, S3+S4 add the
// entry-mode UIs in later slices).

function mk(partial: Partial<FollowUpRule>): FollowUpRule {
  return {
    rule_id: "r" + Math.random().toString(36).slice(2, 8),
    event_code: "evt",
    title_de: "Frist",
    title_en: "Deadline",
    priority: "mandatory",
    is_court_set: false,
    is_spawn: false,
    is_bilateral: false,
    has_condition: false,
    ...partial,
  };
}

describe("groupFollowUps — design §4.2 priority+condition buckets", () => {
  test("groups by priority; conditional takes precedence over priority", () => {
    const rows = [
      mk({ priority: "mandatory" }),
      mk({ priority: "recommended" }),
      mk({ priority: "optional" }),
      mk({ priority: "mandatory", has_condition: true }), // → conditional
      mk({ priority: "optional", has_condition: true }),  // → conditional
    ];
    const g = groupFollowUps(rows);
    expect(g.mandatory.length).toBe(1);
    expect(g.recommended.length).toBe(1);
    expect(g.optional.length).toBe(1);
    expect(g.conditional.length).toBe(2);
  });

  test("unknown priority falls through to optional", () => {
    const g = groupFollowUps([mk({ priority: "informational" })]);
    expect(g.optional.length).toBe(1);
    expect(g.mandatory.length).toBe(0);
  });
});

describe("defaultChecked — pre-checks mandatory + recommended, not conditional/court-set", () => {
  test("mandatory rules pre-checked", () => {
    expect(defaultChecked(mk({ priority: "mandatory" }))).toBe(true);
  });
  test("recommended rules pre-checked", () => {
    expect(defaultChecked(mk({ priority: "recommended" }))).toBe(true);
  });
  test("optional rules unchecked", () => {
    expect(defaultChecked(mk({ priority: "optional" }))).toBe(false);
  });
  test("conditional rules unchecked", () => {
    expect(defaultChecked(mk({ priority: "mandatory", has_condition: true }))).toBe(false);
  });
  test("court-set rules unchecked even when mandatory", () => {
    expect(defaultChecked(mk({ priority: "mandatory", is_court_set: true }))).toBe(false);
  });
  test("spawned rules pre-checked when mandatory", () => {
    expect(defaultChecked(mk({ priority: "mandatory", is_spawn: true }))).toBe(true);
  });
  test("spawned optional rules unchecked", () => {
    expect(defaultChecked(mk({ priority: "optional", is_spawn: true }))).toBe(false);
  });
});
