import { beforeEach, describe, expect, it, vi } from "vitest";
import { db } from "@/lib/db";
import { upsertWooAccount } from "./woo-sso";

vi.mock("@/lib/db", () => ({ db: { $transaction: vi.fn() } }));

describe("WooCommerce account identity", () => {
  const findUnique = vi.fn();
  const userUpdate = vi.fn();
  const userCreate = vi.fn();

  beforeEach(() => {
    vi.clearAllMocks();
    vi.mocked(db.$transaction).mockImplementation(async (callback) => callback({
      user: { findUnique, update: userUpdate, create: userCreate },
      organization: { upsert: vi.fn() },
      organizationMember: { upsert: vi.fn() },
    } as never));
  });

  it("does not attach a different Woo customer to an existing email", async () => {
    findUnique.mockResolvedValueOnce(null).mockResolvedValueOnce({
      id: "user-1", email: "owner@example.com", wooCustomerId: "wc_customer_1",
    });

    await expect(upsertWooAccount({ customerId: "wc_customer_2", email: "owner@example.com" }))
      .rejects.toThrow("already linked to another WooCommerce customer");
    expect(userUpdate).not.toHaveBeenCalled();
    expect(userCreate).not.toHaveBeenCalled();
  });
});
