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

const { mockOptima, mockHandleApiError } = vi.hoisted(() => ({
  mockOptima: {
    company: { count: vi.fn() },
  },
  mockHandleApiError: vi.fn(),
}));

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

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

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

  it("returns null companyCount when no token", async () => {
    const result = await load({
      locals: {},
    } as any);

    expect(result).toEqual({ companyCount: null });
  });

  it("returns company count on success", async () => {
    mockOptima.company.count.mockResolvedValueOnce(42);

    const result = await load({
      locals: { session: { accessToken: "tok" } },
    } as any);

    expect(result).toEqual({ companyCount: 42 });
  });

  it("calls handleApiError on failure", async () => {
    const err = new Error("fail");
    mockOptima.company.count.mockRejectedValueOnce(err);

    await load({
      locals: { session: { accessToken: "tok" } },
    } as any);

    expect(mockHandleApiError).toHaveBeenCalledWith(err);
  });
});
