import { describe, expect, it } from "vitest";
import { InsufficientPermissionError } from "./errors";
import { requirePermission } from "./requirePermission";
import type { CommandContext } from "./types";

describe("requirePermission", () => {
  const ctx: CommandContext = {
    actorId: "user-1",
    permissions: [
      "primitives:createCategory",
      "primitives:activateCategory",
      "inventory:createItem",
    ],
  };

  it("returns ok when permission is present", () => {
    expect(requirePermission(ctx, "primitives:createCategory").ok).toBe(true);
    expect(requirePermission(ctx, "inventory:createItem").ok).toBe(true);
  });

  it("returns InsufficientPermissionError when permission is missing", () => {
    const result = requirePermission(ctx, "primitives:deleteCategory");
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InsufficientPermissionError);
    }
  });

  it("includes actorId and permission key in error", () => {
    const result = requirePermission(ctx, "orders:createOrder");
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error.name).toBe("InsufficientPermissionError");
      expect(result.error.code).toBe("INSUFFICIENT_PERMISSION");
      expect(result.error.message).toContain("user-1");
      expect(result.error.message).toContain("orders:createOrder");
    }
  });

  it("returns error when permissions array is empty", () => {
    const emptyCtx: CommandContext = { actorId: "user-2", permissions: [] };
    const result = requirePermission(emptyCtx, "primitives:createCategory");
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InsufficientPermissionError);
    }
  });
});
