import assert from "node:assert/strict";
import test from "node:test";
import {
  filterSidebarItemsWithForkGroups,
  getForkGroupPresentation,
  groupForkedChatItems,
  shouldRequestChatTitle,
} from "../src/lib/chat-forking.ts";

const root = { kind: "chat", id: "root", parentChatId: null };
const firstFork = { kind: "chat", id: "first-fork", parentChatId: "root" };
const nestedFork = { kind: "chat", id: "nested-fork", parentChatId: "root" };
const search = { kind: "search", id: "search", parentChatId: null };

test("fork groups are positioned by their newest member and always render root first", () => {
  assert.deepEqual(groupForkedChatItems([nestedFork, search, root, firstFork]), [
    [root, nestedFork, firstFork],
    [search],
  ]);
});

test("sidebar filtering keeps a matching fork with its root", () => {
  assert.deepEqual(
    filterSidebarItemsWithForkGroups([search, root, firstFork, nestedFork], (item) => item.id === "nested-fork"),
    [root, nestedFork]
  );
});

test("sidebar filtering keeps all children when their root matches", () => {
  assert.deepEqual(
    filterSidebarItemsWithForkGroups([search, root, firstFork, nestedFork], (item) => item.id === "root"),
    [root, firstFork, nestedFork]
  );
});

test("a filtered family keeps its full-family date and root-owned star state", () => {
  const fullFamily = [
    { ...root, updatedAt: "2026-08-10T00:00:00.000Z", starred: true, starredAt: "2026-08-15T00:00:00.000Z" },
    { ...firstFork, updatedAt: "2026-08-11T00:00:00.000Z", starred: false, starredAt: null },
    { ...nestedFork, updatedAt: "2026-08-16T00:00:00.000Z", starred: false, starredAt: null },
  ];
  const filteredFamily = [fullFamily[0], fullFamily[1]];

  assert.deepEqual(getForkGroupPresentation(filteredFamily, fullFamily), {
    updatedAt: "2026-08-16T00:00:00.000Z",
    starred: true,
    starredAt: "2026-08-15T00:00:00.000Z",
  });
});

test("a fork placeholder title is replaced on its first submitted prompt", () => {
  assert.equal(shouldRequestChatTitle({ title: "Fork of original", titleGenerationPending: true }, false), true);
  assert.equal(shouldRequestChatTitle({ title: "Generated title", titleGenerationPending: false }, false), false);
});

test("title generation remains compatible with untitled chats and deduplicates in-flight requests", () => {
  assert.equal(shouldRequestChatTitle({ title: null, titleGenerationPending: false }, false), true);
  assert.equal(shouldRequestChatTitle({ title: "Fork of original", titleGenerationPending: true }, true), false);
});
