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

const { mockOptima, mockJson, mockError } = vi.hoisted(() => ({
  mockOptima: {
    cw: {
      fetchMembers: vi.fn(),
    },
  },
  mockJson: vi.fn((data, init?) => {
    return new Response(JSON.stringify(data), {
      status: init?.status ?? 200,
      headers: { "Content-Type": "application/json" },
    });
  }),
  mockError: vi.fn((status: number, message: string) => {
    throw { status, body: { message } };
  }),
}));

vi.mock("$lib", () => ({ optima: mockOptima }));
vi.mock("@sveltejs/kit", () => ({
  json: mockJson,
  error: mockError,
}));

import { GET } from "./+server";

describe("GET /api/cw/members", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.spyOn(console, "error").mockImplementation(() => {});
  });

  it("returns 401 with empty data when no access token", async () => {
    const event = { locals: {} };

    GET(event as any);

    expect(mockJson).toHaveBeenCalledWith({ data: [] }, { status: 401 });
  });

  it("returns members on success", async () => {
    const members = [{ id: 1, name: "John" }];
    mockOptima.cw.fetchMembers.mockResolvedValueOnce(members);

    const event = { locals: { session: { accessToken: "tok" } } };

    await GET(event as any);

    expect(mockOptima.cw.fetchMembers).toHaveBeenCalledWith("tok");
    expect(mockJson).toHaveBeenCalledWith({ data: members });
  });

  it("returns 500 with empty data on fetch failure", async () => {
    mockOptima.cw.fetchMembers.mockRejectedValueOnce(new Error("fail"));

    const event = { locals: { session: { accessToken: "tok" } } };

    await GET(event as any);

    expect(mockJson).toHaveBeenCalledWith({ data: [] }, { status: 500 });
  });
});
