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

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

  const noteId = Number(params.noteId);
  if (isNaN(noteId)) throw error(400, "Invalid note ID");

  const body = await request.json();
  if (!body.text?.trim() && body.flagged === undefined) {
    throw error(400, "At least text or flagged must be provided");
  }

  const payload: { text?: string; flagged?: boolean } = {};
  if (body.text?.trim()) payload.text = body.text.trim();
  if (body.flagged !== undefined) payload.flagged = body.flagged;

  try {
    const result = await optima.sales.updateNote(
      accessToken,
      params.id,
      noteId,
      payload,
    );
    return json(result);
  } catch (err: unknown) {
    console.error("Failed to update note:", err);
    const status =
      err && typeof err === "object" && "status" in err
        ? (err as { status: number }).status
        : 500;
    throw error(status, "Failed to update note");
  }
};

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

  const noteId = Number(params.noteId);
  if (isNaN(noteId)) throw error(400, "Invalid note ID");

  try {
    const result = await optima.sales.deleteNote(
      accessToken,
      params.id,
      noteId,
    );
    return json(result);
  } catch (err: unknown) {
    console.error("Failed to delete note:", err);
    const status =
      err && typeof err === "object" && "status" in err
        ? (err as { status: number }).status
        : 500;
    throw error(status, "Failed to delete note");
  }
};
