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

const { mockApi } = vi.hoisted(() => ({
  mockApi: {
    get: vi.fn(),
  },
}));

vi.mock("$lib/optima-api/axios", () => ({
  default: mockApi,
  api: mockApi,
}));

import { cw, type CWMember } from "./cw";

describe("cw module", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("fetchMembers calls /v1/cw/members with auth header", async () => {
    const mockMembers: CWMember[] = [
      {
        id: 1,
        identifier: "jdoe",
        firstName: "John",
        lastName: "Doe",
        name: "John Doe",
        officeEmail: "jdoe@example.com",
        inactive: false,
      },
    ];
    mockApi.get.mockResolvedValueOnce({ data: { data: mockMembers } });

    const result = await cw.fetchMembers("test-token");

    expect(mockApi.get).toHaveBeenCalledWith("/v1/cw/members", {
      params: {},
      headers: { Authorization: "Bearer test-token" },
    });
    expect(result).toEqual(mockMembers);
  });

  it("fetchMembers passes active=false param when specified", async () => {
    mockApi.get.mockResolvedValueOnce({ data: { data: [] } });

    await cw.fetchMembers("test-token", { active: false });

    expect(mockApi.get).toHaveBeenCalledWith("/v1/cw/members", {
      params: { active: "false" },
      headers: { Authorization: "Bearer test-token" },
    });
  });

  it("fetchMembers does not set active param when active is true", async () => {
    mockApi.get.mockResolvedValueOnce({ data: { data: [] } });

    await cw.fetchMembers("test-token", { active: true });

    expect(mockApi.get).toHaveBeenCalledWith("/v1/cw/members", {
      params: {},
      headers: { Authorization: "Bearer test-token" },
    });
  });

  it("fetchMembers propagates API errors", async () => {
    mockApi.get.mockRejectedValueOnce(new Error("Network error"));

    await expect(cw.fetchMembers("test-token")).rejects.toThrow(
      "Network error",
    );
  });

  it("fetchMembers returns empty array when API returns empty", async () => {
    mockApi.get.mockResolvedValueOnce({ data: { data: [] } });

    const result = await cw.fetchMembers("test-token");

    expect(result).toEqual([]);
  });
});
