import { beforeEach, describe, expect, it, vi } from "vitest";

const apiClient = {
  post: vi.fn(),
  put: vi.fn(),
};

vi.mock("./apiClient", () => ({
  default: apiClient,
}));

describe("orgfront adminApi user tenant payloads", () => {
  beforeEach(() => {
    apiClient.post.mockReset();
    apiClient.put.mockReset();
  });

  it("sends tenantSlug without remapping it to companyCode when creating a user", async () => {
    const { createUser } = await import("./adminApi");
    apiClient.post.mockResolvedValue({ data: {} });

    await createUser({
      email: "user@test.com",
      name: "Test User",
      tenantSlug: "test-tenant",
    });

    expect(apiClient.post).toHaveBeenCalledWith(
      "/v1/admin/users",
      expect.objectContaining({ tenantSlug: "test-tenant" }),
    );
    expect(apiClient.post.mock.calls[0][1]).not.toHaveProperty("companyCode");
  });

  it("sends tenantSlug without remapping it to companyCode when updating a user", async () => {
    const { updateUser } = await import("./adminApi");
    apiClient.put.mockResolvedValue({ data: {} });

    await updateUser("user-id", { tenantSlug: "new-tenant" });

    expect(apiClient.put).toHaveBeenCalledWith(
      "/v1/admin/users/user-id",
      expect.objectContaining({ tenantSlug: "new-tenant" }),
    );
    expect(apiClient.put.mock.calls[0][1]).not.toHaveProperty("companyCode");
  });

  it("keeps tenantSlug payloads unchanged for bulk user APIs", async () => {
    const { bulkCreateUsers, bulkUpdateUsers } = await import("./adminApi");
    apiClient.post.mockResolvedValue({ data: {} });
    apiClient.put.mockResolvedValue({ data: {} });

    await bulkCreateUsers([
      {
        email: "user@test.com",
        name: "Test User",
        tenantSlug: "test-tenant",
        metadata: {},
      },
    ]);
    await bulkUpdateUsers({
      userIds: ["user-id"],
      tenantSlug: "new-tenant",
    });

    expect(apiClient.post.mock.calls[0][1].users[0]).toMatchObject({
      tenantSlug: "test-tenant",
    });
    expect(apiClient.post.mock.calls[0][1].users[0]).not.toHaveProperty(
      "companyCode",
    );
    expect(apiClient.put.mock.calls[0][1]).toMatchObject({
      tenantSlug: "new-tenant",
    });
    expect(apiClient.put.mock.calls[0][1]).not.toHaveProperty("companyCode");
  });
});
