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

const { mockOptima, mockJson, mockError } = vi.hoisted(() => ({
  mockOptima: {
    sales: { fetchWorkflowHistory: 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 /sales/opportunity/[id]/workflow/history", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.spyOn(console, "error").mockImplementation(() => {});
  });

  it("throws 401 when no access token", async () => {
    const event = {
      locals: {},
      params: { id: "opp-1" },
      url: new URL("http://localhost/workflow/history"),
    };

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

  it("fetches workflow history with type param", async () => {
    mockOptima.sales.fetchWorkflowHistory.mockResolvedValueOnce({
      data: [{ action: "approve" }],
    });

    const event = {
      locals: { session: { accessToken: "tok" } },
      params: { id: "opp-1" },
      url: new URL("http://localhost/workflow/history?type=approval"),
    };

    await GET(event as any);

    expect(mockOptima.sales.fetchWorkflowHistory).toHaveBeenCalledWith(
      "tok",
      "opp-1",
      "approval",
    );
    expect(mockJson).toHaveBeenCalledWith({
      data: [{ action: "approve" }],
    });
  });

  it("passes undefined when type param is absent", async () => {
    mockOptima.sales.fetchWorkflowHistory.mockResolvedValueOnce({ data: [] });

    const event = {
      locals: { session: { accessToken: "tok" } },
      params: { id: "opp-1" },
      url: new URL("http://localhost/workflow/history"),
    };

    await GET(event as any);

    expect(mockOptima.sales.fetchWorkflowHistory).toHaveBeenCalledWith(
      "tok",
      "opp-1",
      undefined,
    );
  });

  it("throws on failure with API error message", async () => {
    mockOptima.sales.fetchWorkflowHistory.mockRejectedValueOnce({
      status: 500,
      response: { data: { message: "Server broke" } },
    });

    const event = {
      locals: { session: { accessToken: "tok" } },
      params: { id: "opp-1" },
      url: new URL("http://localhost/workflow/history"),
    };

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