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

const { mockOptima, mockJson, mockError } = vi.hoisted(() => ({
  mockOptima: {
    company: { fetchSites: 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]/sites", () => {
  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: [] }, { status: 401 });
  });

  it("fetches sites successfully", async () => {
    mockOptima.company.fetchSites.mockResolvedValueOnce({
      data: [{ id: "s1", name: "Main" }],
    });

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

    await GET(event as any);

    expect(mockOptima.company.fetchSites).toHaveBeenCalledWith("tok", "123");
    expect(mockJson).toHaveBeenCalledWith({
      data: [{ id: "s1", name: "Main" }],
    });
  });

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

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

    await GET(event as any);

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