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

const { mockOptima, mockJson, mockError } = vi.hoisted(() => ({
  mockOptima: {
    sales: { deleteOpportunity: 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 { DELETE } from "./+server";

describe("DELETE /sales/opportunity/[id]", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.spyOn(console, "error").mockImplementation(() => {});
  });

  it("throws 401 when no access token", async () => {
    const event = { locals: {}, params: { id: "opp-1" } };
    await expect(DELETE(event as any)).rejects.toEqual(
      expect.objectContaining({ status: 401 }),
    );
  });

  it("deletes opportunity successfully", async () => {
    mockOptima.sales.deleteOpportunity.mockResolvedValueOnce({ success: true });

    const event = {
      locals: { session: { accessToken: "tok" } },
      params: { id: "opp-1" },
    };

    await DELETE(event as any);

    expect(mockOptima.sales.deleteOpportunity).toHaveBeenCalledWith(
      "tok",
      "opp-1",
    );
    expect(mockJson).toHaveBeenCalledWith({ success: true });
  });

  it("throws error on failure", async () => {
    mockOptima.sales.deleteOpportunity.mockRejectedValueOnce({
      status: 404,
    });

    const event = {
      locals: { session: { accessToken: "tok" } },
      params: { id: "opp-1" },
    };

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