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

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

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

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

    it("returns workflow status", async () => {
      mockOptima.sales.fetchWorkflowStatus.mockResolvedValueOnce({
        data: { state: "draft" },
      });

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

      await GET(event as any);

      expect(mockOptima.sales.fetchWorkflowStatus).toHaveBeenCalledWith(
        "tok",
        "opp-1",
      );
      expect(mockJson).toHaveBeenCalledWith({ data: { state: "draft" } });
    });

    it("throws on failure", async () => {
      mockOptima.sales.fetchWorkflowStatus.mockRejectedValueOnce({
        status: 500,
        response: { data: { message: "Internal error" } },
      });

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

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

  describe("POST", () => {
    it("throws 401 when no access token", async () => {
      const event = {
        locals: {},
        params: { id: "opp-1" },
        request: { json: vi.fn().mockResolvedValue({ action: "approve" }) },
      };
      await expect(POST(event as any)).rejects.toBeDefined();
    });

    it("throws 400 when action is missing", async () => {
      const event = {
        locals: { session: { accessToken: "tok" } },
        params: { id: "opp-1" },
        request: { json: vi.fn().mockResolvedValue({}) },
      };

      await expect(POST(event as any)).rejects.toEqual(
        expect.objectContaining({ status: 400 }),
      );
    });

    it("dispatches workflow action successfully", async () => {
      mockOptima.sales.dispatchWorkflowAction.mockResolvedValueOnce({
        data: { state: "approved" },
      });

      const event = {
        locals: { session: { accessToken: "tok" } },
        params: { id: "opp-1" },
        request: {
          json: vi
            .fn()
            .mockResolvedValue({ action: "approve", payload: { note: "ok" } }),
        },
      };

      await POST(event as any);

      expect(mockOptima.sales.dispatchWorkflowAction).toHaveBeenCalledWith(
        "tok",
        "opp-1",
        "approve",
        { note: "ok" },
      );
      expect(mockJson).toHaveBeenCalledWith({ data: { state: "approved" } });
    });

    it("returns error response data on workflow failure", async () => {
      mockOptima.sales.dispatchWorkflowAction.mockRejectedValueOnce({
        status: 422,
        response: {
          data: {
            status: 422,
            message: "Cannot transition",
            errors: ["Invalid state"],
          },
        },
      });

      const event = {
        locals: { session: { accessToken: "tok" } },
        params: { id: "opp-1" },
        request: {
          json: vi.fn().mockResolvedValue({ action: "approve" }),
        },
      };

      await POST(event as any);

      expect(mockJson).toHaveBeenCalledWith(
        {
          status: 422,
          message: "Cannot transition",
          errors: ["Invalid state"],
        },
        { status: 422 },
      );
    });
  });
});
