import { optima } from "$lib";
import { json, error } from "@sveltejs/kit";
import type { RequestHandler } from "./$types";

/** POST /sales/opportunity/[id]/notes — create a note */
export const POST: RequestHandler = async ({ params, request, locals }) => {
  const accessToken = locals.session?.accessToken;
  if (!accessToken) throw error(401, "Unauthorized");

  const body = await request.json();
  if (!body.text?.trim()) throw error(400, "Note text is required");

  try {
    const result = await optima.sales.createNote(accessToken, params.id, {
      text: body.text.trim(),
      flagged: body.flagged ?? false,
    });
    return json(result, { status: 201 });
  } catch (err: unknown) {
    console.error("Failed to create note:", err);
    const status =
      err && typeof err === "object" && "status" in err
        ? (err as { status: number }).status
        : 500;
    throw error(status, "Failed to create note");
  }
};
