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

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

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

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

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

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

  it("creates note successfully", async () => {
    const created = { id: 1, text: "A note" };
    mockOptima.sales.createNote.mockResolvedValueOnce(created);

    const event = {
      locals: { session: { accessToken: "tok" } },
      params: { id: "opp-1" },
      request: {
        json: vi.fn().mockResolvedValue({ text: "A note", flagged: true }),
      },
    };

    await POST(event as any);

    expect(mockOptima.sales.createNote).toHaveBeenCalledWith("tok", "opp-1", {
      text: "A note",
      flagged: true,
    });
    expect(mockJson).toHaveBeenCalledWith(created, { status: 201 });
  });

  it("defaults flagged to false", async () => {
    mockOptima.sales.createNote.mockResolvedValueOnce({ id: 1 });

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

    await POST(event as any);

    expect(mockOptima.sales.createNote).toHaveBeenCalledWith("tok", "opp-1", {
      text: "Note",
      flagged: false,
    });
  });
});
