import { describe, expect, it } from "vitest";
import type { FileTreeSelectionState } from "./selection";
import {
  createEmptyFileTreeSelectionState,
  materializeRendererSelectionSnapshot,
  resolveActiveFileTreeSelection,
} from "./selection-source";

function selection(
  selectedRowIds: string[],
  anchorRowId: string | null,
  focusedRowId: string | null,
): FileTreeSelectionState {
  return {
    selectedRowIds: new Set(selectedRowIds),
    anchorRowId,
    focusedRowId,
  };
}

describe("selection-source", () => {
  it("rust_family 应优先消费 renderer selection snapshot", () => {
    const legacySelection = selection(["legacy"], "legacy", "legacy");
    const rendererSelection = selection(["renderer"], "renderer", "renderer");

    expect(
      resolveActiveFileTreeSelection({
        preferRendererSnapshot: true,
        legacySelection,
        rendererSelection,
      }),
    ).toBe(rendererSelection);

    expect(
      resolveActiveFileTreeSelection({
        preferRendererSnapshot: false,
        legacySelection,
        rendererSelection,
      }),
    ).toBe(legacySelection);
  });

  it("renderer event snapshot 只过滤未知 row，不在宿主侧重算 focus/anchor", () => {
    const snapshot = materializeRendererSelectionSnapshot({
      payload: {
        selectedRowIds: ["doc:a", "missing"],
        anchorRowId: "missing",
        focusedRowId: "doc:a",
      },
      hasRowId: (rowId) => rowId === "doc:a",
    });

    expect(Array.from(snapshot.selectedRowIds)).toEqual(["doc:a"]);
    expect(snapshot.anchorRowId).toBeNull();
    expect(snapshot.focusedRowId).toBe("doc:a");
  });

  it("空 selection 工厂应返回互不共享的 Set 实例", () => {
    const a = createEmptyFileTreeSelectionState();
    const b = createEmptyFileTreeSelectionState();

    a.selectedRowIds.add("doc:a");

    expect(a.selectedRowIds.has("doc:a")).toBe(true);
    expect(b.selectedRowIds.has("doc:a")).toBe(false);
    expect(a.selectedRowIds).not.toBe(b.selectedRowIds);
  });
});
