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

const { mockOptima, mockCheckPermissions, mockHandleApiError } = vi.hoisted(
  () => ({
    mockOptima: {
      procurement: { fetchMany: vi.fn() },
    },
    mockCheckPermissions: vi.fn(),
    mockHandleApiError: vi.fn(),
  }),
);

vi.mock("$lib", () => ({ optima: mockOptima }));
vi.mock("$lib/permissions", () => ({
  checkPermissions: mockCheckPermissions,
}));
vi.mock("$lib/optima-api/errorHandler", () => ({
  handleApiError: mockHandleApiError,
}));

import { load } from "./+page.server";

describe("procurement/catalog +page.server.ts load", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("returns empty data when no token", async () => {
    const result = await load({
      locals: {},
      url: new URL("http://localhost/procurement/catalog"),
    } as any);

    expect(result).toMatchObject({
      items: [],
      totalPages: 1,
      currentPage: 1,
      totalRecords: 0,
      search: "",
    });
  });

  it("fetches catalog items with pagination", async () => {
    mockOptima.procurement.fetchMany.mockResolvedValueOnce({
      data: [{ id: "item-1" }],
      meta: {
        pagination: { totalPages: 2, currentPage: 1, totalRecords: 45 },
      },
    });
    mockCheckPermissions.mockResolvedValueOnce({
      "procurement.catalog.fetch.many": true,
    });

    const result = await load({
      locals: { session: { accessToken: "tok" } },
      url: new URL("http://localhost/procurement/catalog?page=1&search=widget"),
    } as any);

    expect(result).toMatchObject({
      items: [{ id: "item-1" }],
      totalPages: 2,
      totalRecords: 45,
      search: "widget",
    });
  });

  it("passes includeInactive when param is true", async () => {
    mockOptima.procurement.fetchMany.mockResolvedValueOnce({
      data: [],
      meta: {
        pagination: { totalPages: 1, currentPage: 1, totalRecords: 0 },
      },
    });
    mockCheckPermissions.mockResolvedValueOnce({});

    await load({
      locals: { session: { accessToken: "tok" } },
      url: new URL("http://localhost/procurement/catalog?includeInactive=true"),
    } as any);

    expect(mockOptima.procurement.fetchMany).toHaveBeenCalledWith(
      "tok",
      1,
      { search: "", includeInactive: true },
      30,
    );
  });
});
