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

const { mockOptima, mockJson, mockError } = vi.hoisted(() => ({
  mockOptima: {
    procurement: { fetchMany: vi.fn() },
  },
  mockJson: vi.fn((data, init?) => {
    return new Response(JSON.stringify(data), {
      status: init?.status ?? 200,
    });
  }),
  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 /procurement/catalog/search", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.spyOn(console, "error").mockImplementation(() => {});
  });

  it("throws 401 when no access token", async () => {
    const event = {
      locals: {},
      url: new URL("http://localhost/search?q=widget"),
    };
    await expect(GET(event as any)).rejects.toBeDefined();
  });

  it("returns empty data when query is empty", async () => {
    const event = {
      locals: { session: { accessToken: "tok" } },
      url: new URL("http://localhost/search"),
    };

    GET(event as any);

    expect(mockJson).toHaveBeenCalledWith({ data: [] });
    expect(mockOptima.procurement.fetchMany).not.toHaveBeenCalled();
  });

  it("searches catalog items", async () => {
    mockOptima.procurement.fetchMany.mockResolvedValueOnce({
      data: [{ id: "item-1", name: "Widget" }],
    });

    const event = {
      locals: { session: { accessToken: "tok" } },
      url: new URL("http://localhost/search?q=widget"),
    };

    await GET(event as any);

    expect(mockOptima.procurement.fetchMany).toHaveBeenCalledWith(
      "tok",
      1,
      { search: "widget", includeInactive: true },
      20,
    );
    expect(mockJson).toHaveBeenCalledWith({
      data: [{ id: "item-1", name: "Widget" }],
    });
  });

  it("throws on failure", async () => {
    mockOptima.procurement.fetchMany.mockRejectedValueOnce({
      status: 500,
    });

    const event = {
      locals: { session: { accessToken: "tok" } },
      url: new URL("http://localhost/search?q=widget"),
    };

    await expect(GET(event as any)).rejects.toBeDefined();
  });
});
