import assert from "node:assert/strict";
import test from "node:test";
import { resolveSidebarSelectionAfterRefresh } from "../src/lib/sidebar-selection.ts";

const workspaceItems = [
  { type: "chat", id: "completed-chat" },
  { type: "chat", id: "selected-chat" },
  { type: "search", id: "selected-search" },
];

test("a collection refresh preserves the current thread selection", () => {
  assert.deepEqual(
    resolveSidebarSelectionAfterRefresh({ kind: "chat", id: "selected-chat" }, workspaceItems),
    { kind: "chat", id: "selected-chat" }
  );
});

test("an initial route selection cannot override a current thread selection", () => {
  assert.deepEqual(
    resolveSidebarSelectionAfterRefresh(
      { kind: "search", id: "selected-search" },
      workspaceItems,
      { initialSelection: { kind: "chat", id: "completed-chat" }, selectFallback: true }
    ),
    { kind: "search", id: "selected-search" }
  );
});

test("a collection refresh preserves an intentionally empty selection", () => {
  assert.equal(resolveSidebarSelectionAfterRefresh(null, workspaceItems), null);
});

test("initial load can select the URL thread or fall back to the first item", () => {
  assert.deepEqual(
    resolveSidebarSelectionAfterRefresh(null, workspaceItems, {
      initialSelection: { kind: "search", id: "selected-search" },
      selectFallback: true,
    }),
    { kind: "search", id: "selected-search" }
  );
  assert.deepEqual(resolveSidebarSelectionAfterRefresh(null, workspaceItems, { selectFallback: true }), {
    kind: "chat",
    id: "completed-chat",
  });
});
