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

const { mockOptima, mockJson, mockError } = vi.hoisted(() => ({
  mockOptima: {
    company: { fetch: 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 /api/companies/[id]/details", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.spyOn(console, "error").mockImplementation(() => {});
  });

  it("returns 401 when no token", async () => {
    const event = { locals: {}, params: { id: "123" } };
    GET(event as any);
    expect(mockJson).toHaveBeenCalledWith({ data: null }, { status: 401 });
  });

  it("fetches company with contacts and address", async () => {
    mockOptima.company.fetch.mockResolvedValueOnce({
      data: { id: "123", name: "Acme" },
    });

    const event = {
      locals: { session: { accessToken: "tok" } },
      params: { id: "123" },
    };

    await GET(event as any);

    expect(mockOptima.company.fetch).toHaveBeenCalledWith("tok", "123", {
      includeAllContacts: true,
      includeAddress: true,
      includeAllAddresses: true,
    });
    expect(mockJson).toHaveBeenCalledWith({
      data: { id: "123", name: "Acme" },
    });
  });

  it("returns 500 on API failure", async () => {
    mockOptima.company.fetch.mockRejectedValueOnce(new Error("fail"));

    const event = {
      locals: { session: { accessToken: "tok" } },
      params: { id: "123" },
    };

    await GET(event as any);

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