import { describe, expect, it } from "vitest";
import { buildVisibleDocumentIds } from "../../../convex/_utils/documentVisibility";

describe("buildVisibleDocumentIds", () => {
  const docs = [
    { id: "owner-root", user_id: "u1", parent_id: null, access_scope: "private", deleted_at: null },
    { id: "public-root", user_id: "u2", parent_id: null, access_scope: "public", deleted_at: null },
    { id: "shared-root", user_id: "u2", parent_id: null, access_scope: "private", deleted_at: null },
    { id: "shared-child", user_id: "u2", parent_id: "shared-root", access_scope: "private", deleted_at: null },
    { id: "group-root", user_id: "u3", parent_id: null, access_scope: "private", deleted_at: null },
    { id: "group-child", user_id: "u3", parent_id: "group-root", access_scope: "private", deleted_at: null },
    { id: "deleted-public", user_id: "u4", parent_id: null, access_scope: "public", deleted_at: "2026-05-12T00:00:00.000Z" },
  ] as const;

  it("允许 owner、public、直接分享与继承分享的文档可见", () => {
    const visible = buildVisibleDocumentIds({
      userId: "u1",
      docs,
      directShares: [{ document_id: "shared-root", include_descendants: true }],
      directGroupShares: [],
    });

    expect(Array.from(visible).sort()).toEqual([
      "owner-root",
      "public-root",
      "shared-child",
      "shared-root",
    ]);
  });

  it("允许群组分享向下继承，但不会包含已删除文档", () => {
    const visible = buildVisibleDocumentIds({
      userId: "u9",
      docs,
      directShares: [],
      directGroupShares: [{ document_id: "group-root", include_descendants: true }],
      includeDeletedDocuments: false,
    });

    expect(Array.from(visible).sort()).toEqual([
      "group-child",
      "group-root",
      "public-root",
    ]);
    expect(visible.has("deleted-public")).toBe(false);
  });
});
