import { describe, expect, test } from "bun:test";
import {
  EDITOR_HABITS,
  backfillError,
  historicalDays,
  validateEditor,
  validateTasks,
} from "./editing-model";

describe("design-system editors", () => {
  test("all initial configurations are valid", () => {
    for (const habit of EDITOR_HABITS)
      expect(validateEditor(habit.config)).toBeNull();
  });
  test("requires a name, valid target, and nonempty weekday schedule", () => {
    const config = EDITOR_HABITS[0]!.config;
    expect(validateEditor({ ...config, name: " " })).not.toBeNull();
    if (config.method !== "count") throw new Error("Expected count fixture");
    for (const target of [0, 1.5, NaN, 10001])
      expect(validateEditor({ ...config, target })).not.toBeNull();
    expect(
      validateEditor({ ...config, schedule: { type: "weekdays", days: [] } }),
    ).not.toBeNull();
  });
  test("validates task names and independent recurrence", () => {
    expect(
      validateTasks([{ id: "1", name: "", schedule: { type: "daily" } }]),
    ).not.toBeNull();
    expect(
      validateTasks([
        {
          id: "1",
          name: "Read",
          schedule: { type: "interval", every: 0, anchor: "2026-09-04" },
        },
      ]),
    ).not.toBeNull();
    expect(validateTasks([])).toBeNull();
  });
  test("backfills reject today, future, nonexistent and unscheduled dates", () => {
    for (const date of [
      "2026-09-04",
      "2026-09-05",
      "2026-02-30",
      "2025-09-30",
      "",
    ])
      expect(backfillError("water", date, 1)).not.toBeNull();
    const notDue = historicalDays("water").find(
      (day) => day.state === "not-due",
    )!;
    expect(backfillError("water", notDue.date, 1)).not.toBeNull();
  });
  test("corrections allow zero and over-target counts but reject invalid totals", () => {
    for (const value of [0, 8, 12, 1_000_000_000])
      expect(backfillError("water", "2026-09-03", value)).toBeNull();
    for (const value of [-1, 1.5, NaN, 1_000_000_001])
      expect(backfillError("water", "2026-09-03", value)).not.toBeNull();
    expect(backfillError("reading", "2026-09-03", 2)).not.toBeNull();
    expect(backfillError("tasks", "2026-09-03", 4)).not.toBeNull();
  });
  test("editing a current target or task list does not rewrite historical requirements", () => {
    const copy = structuredClone(EDITOR_HABITS);
    const water = copy[0]!.config;
    const tasks = copy[2]!.config;
    if (water.method === "count") water.target = 12;
    if (tasks.method === "tasks") tasks.tasks.pop();
    expect(historicalDays("water")[0]!.target).toBe(8);
    expect(historicalDays("tasks")[0]!.target).toBe(3);
  });
});
