import { describe, expect, it } from "vitest";
import { createContext } from "./createContext";

describe("createContext", () => {
  describe("invoker", () => {
    it("uses invoker when present", () => {
      const ctx = createContext({
        invoker: {
          id: "invoker-1",
          attributes: {
            permissions: ["user-management:user:createUser"],
            companyId: "company-1",
          },
        },
        user: {
          id: "user-1",
          attributes: { permissions: ["user-management:user:activateUser"] },
        },
      });

      expect(ctx.actorId).toBe("invoker-1");
      expect(ctx.permissions).toEqual(["user-management:user:createUser"]);
      expect(ctx.companyId).toBe("company-1");
    });

    it("returns unauthenticated context when invoker is null", () => {
      const ctx = createContext({
        invoker: null,
        user: {
          id: "user-1",
          attributes: { permissions: ["user-management:user:createUser"] },
        },
      });

      expect(ctx.actorId).toBe("00000000-0000-0000-0000-000000000000");
      expect(ctx.permissions).toEqual([]);
      expect(ctx.companyId).toBeNull();
    });
  });

  describe("user fallback (invoker absent)", () => {
    it("uses permissions array attribute when present", () => {
      const ctx = createContext({
        user: {
          id: "user-1",
          attributes: {
            permissions: ["user-management:user:createUser", "user-management:user:activateUser"],
          },
        },
      });

      expect(ctx.actorId).toBe("user-1");
      expect(ctx.permissions).toEqual([
        "user-management:user:createUser",
        "user-management:user:activateUser",
      ]);
    });

    it("returns empty permissions when attributes exists but permissions is absent", () => {
      const ctx = createContext({
        user: {
          id: "user-1",
          attributes: {},
        },
      });

      expect(ctx.actorId).toBe("user-1");
      expect(ctx.permissions).toEqual([]);
    });

    it("returns empty permissions when attributes is null", () => {
      const ctx = createContext({
        user: { id: "user-1", attributes: null },
      });

      expect(ctx.actorId).toBe("user-1");
      expect(ctx.permissions).toEqual([]);
    });
  });
});
