import { describe, expect, it } from "vitest";
import {
  buildSavePermissionsRequest,
  clonePermissionDraft,
  createPermissionEntry,
  hasDuplicateSubjects,
  transitionVisibility,
} from "../permissionState";

const org = createPermissionEntry("ORG", "2", "通信部");
const user = createPermissionEntry("USER", "3", "普通用户");

describe("F6 permission draft state", () => {
  it("creates visible safe defaults without silent elevated actions", () => {
    expect(org).toMatchObject({
      canView: true,
      canDownload: false,
      canEdit: false,
      canManagePermission: false,
      canDelete: false,
    });
  });

  it("detects duplicate subjects by type and ID", () => {
    expect(hasDuplicateSubjects([org, { ...org }])).toBe(true);
    expect(hasDuplicateSubjects([org, user])).toBe(false);
  });

  it("clears every ACL entry for ALL_AUTHENTICATED", () => {
    expect(transitionVisibility([org, user], "ALL_AUTHENTICATED"))
      .toEqual([]);
  });

  it("removes USER entries for ORGANIZATION", () => {
    expect(transitionVisibility([org, user], "ORGANIZATION"))
      .toEqual([org]);
  });

  it("keeps mixed entries for CUSTOM", () => {
    expect(transitionVisibility([org, user], "CUSTOM"))
      .toEqual([org, user]);
  });

  it("builds a complete save set without id or subjectName", () => {
    const request = buildSavePermissionsRequest({
      visibilityType: "CUSTOM",
      documentRowVersion: 4,
      entries: [org, user],
    });
    expect(request.entries).toHaveLength(2);
    expect(request.entries[0]).toEqual({
      subjectType: "ORG",
      subjectId: "2",
      canView: true,
      canDownload: false,
      canEdit: false,
      canManagePermission: false,
      canDelete: false,
    });
    expect(request.entries[0]).not.toHaveProperty("id");
    expect(request.entries[0]).not.toHaveProperty("subjectName");
  });

  it("rejects empty ORGANIZATION permission sets", () => {
    expect(() => buildSavePermissionsRequest({
      visibilityType: "ORGANIZATION",
      documentRowVersion: 1,
      entries: [],
    })).toThrow("至少需要一个组织");
  });

  it("rejects duplicate subjects before PUT", () => {
    expect(() => buildSavePermissionsRequest({
      visibilityType: "CUSTOM",
      documentRowVersion: 1,
      entries: [org, { ...org }],
    })).toThrow("不能重复添加");
  });

  it("clones server detail so reset baselines are isolated", () => {
    const detail = {
      documentId: "3",
      sourceDocumentId: "3",
      inherited: false,
      visibilityType: "CUSTOM" as const,
      documentRowVersion: 2,
      entries: [{ ...org, id: "10" }],
    };
    const draft = clonePermissionDraft(detail);
    draft.entries[0].canDelete = true;
    expect(detail.entries[0].canDelete).toBe(false);
  });
});

