import assert from "node:assert/strict";
import { test } from "bun:test";
import { deriveEffectiveTaskTimeRanges, type TaskTreeTimedNode } from "./tasktree-time-range";

function node(id: string, parentId: string | null, startAt: string | null, dueAt: string | null): TaskTreeTimedNode {
  return { id, parentId, startAt, dueAt };
}

test("父级范围从最早子节点开始并保留自身更晚的截止时间", () => {
  const ranges = deriveEffectiveTaskTimeRanges([
    node("R4", null, "2026-07-19T00:00:00.000Z", "2026-07-21T00:00:00.000Z"),
    node("R4.1", "R4", "2026-07-18T20:00:00.000Z", "2026-07-18T21:00:00.000Z"),
  ]);
  assert.deepEqual(ranges.get("R4"), {
    startAt: "2026-07-18T20:00:00.000Z",
    dueAt: "2026-07-21T00:00:00.000Z",
  });
});

test("父级范围包含多层后代节点", () => {
  const ranges = deriveEffectiveTaskTimeRanges([
    node("R1", null, "2026-07-20T00:00:00.000Z", "2026-07-20T01:00:00.000Z"),
    node("R1.1", "R1", null, null),
    node("R1.1.1", "R1.1", "2026-07-17T00:00:00.000Z", "2026-07-22T00:00:00.000Z"),
  ]);
  assert.deepEqual(ranges.get("R1"), {
    startAt: "2026-07-17T00:00:00.000Z",
    dueAt: "2026-07-22T00:00:00.000Z",
  });
  assert.deepEqual(ranges.get("R1.1"), ranges.get("R1.1.1"));
});

test("无时间信息的分支保持无时间范围", () => {
  const ranges = deriveEffectiveTaskTimeRanges([
    node("R2", null, null, null),
    node("R2.1", "R2", null, null),
  ]);
  assert.deepEqual(ranges.get("R2"), { startAt: null, dueAt: null });
});
