import test from "node:test";
import assert from "node:assert/strict";
import { mergeThreadPage, threadTitle, threadsForAccount } from "./thread-library.js";

test("thread library merges pages newest-first and replaces duplicates", () => {
  const current = [
    { id: "old", updatedAt: "2026-06-28T00:00:00.000Z", preview: "Old" },
    { id: "same", updatedAt: "2026-06-27T00:00:00.000Z", preview: "Before" }
  ];
  const incoming = [
    { id: "new", updatedAt: "2026-06-29T00:00:00.000Z", preview: "New" },
    { id: "same", updatedAt: "2026-06-30T00:00:00.000Z", preview: "After" }
  ];

  assert.deepEqual(mergeThreadPage(current, incoming).map((thread) => thread.id), [
    "same", "new", "old"
  ]);
  assert.equal(mergeThreadPage(current, incoming)[0].preview, "After");
});

test("thread library keeps identical ids from different owners", () => {
  const result = mergeThreadPage([], [
    { id: "same", ownerId: "a", updatedAt: "2026-01-01T00:00:00.000Z" },
    { id: "same", ownerId: "b", updatedAt: "2026-01-02T00:00:00.000Z" }
  ]);
  assert.deepEqual(result.map((item) => item.ownerId), ["b", "a"]);
});

test("thread library resets rows when account changes", () => {
  const rows = [{ id: "thread-a" }];
  assert.deepEqual(threadsForAccount("account-a", "account-b", rows), []);
  assert.equal(threadsForAccount("account-a", "account-a", rows), rows);
});

test("thread title falls back from name to preview to New chat", () => {
  assert.equal(threadTitle({ name: "Named", preview: "Preview" }), "Named");
  assert.equal(threadTitle({ preview: "Preview" }), "Preview");
  assert.equal(threadTitle({}), "New chat");
});
