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

describe("planInvitationApplication", () => {
  it("translates a single pending invitation into one membership insert + invitation delete", () => {
    const plan = planInvitationApplication({
      userId: 100n,
      invitations: [
        { id: 1n, portfolioId: 200n, role: "read" },
      ],
      existingPortfolioIds: new Set<bigint>(),
    });

    expect(plan.memberships).toEqual([
      { portfolioId: 200n, userId: 100n, role: "read" },
    ]);
    expect(plan.invitationsToDelete).toEqual([1n]);
  });

  it("skips the membership insert if the user is already a member of that portfolio, but still deletes the stale invitation", () => {
    const plan = planInvitationApplication({
      userId: 100n,
      invitations: [
        { id: 1n, portfolioId: 200n, role: "read" },
      ],
      existingPortfolioIds: new Set<bigint>([200n]),
    });

    expect(plan.memberships).toEqual([]);
    expect(plan.invitationsToDelete).toEqual([1n]);
  });

  it("handles invitations to several portfolios in one application", () => {
    const plan = planInvitationApplication({
      userId: 100n,
      invitations: [
        { id: 1n, portfolioId: 200n, role: "read" },
        { id: 2n, portfolioId: 300n, role: "write" },
        { id: 3n, portfolioId: 400n, role: "admin" },
      ],
      existingPortfolioIds: new Set<bigint>([300n]),
    });

    expect(plan.memberships).toEqual([
      { portfolioId: 200n, userId: 100n, role: "read" },
      { portfolioId: 400n, userId: 100n, role: "admin" },
    ]);
    expect(plan.invitationsToDelete).toEqual([1n, 2n, 3n]);
  });
});
