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

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

  const body = await request.json();

  try {
    const result = await optima.sales.addTimeToActivity(
      accessToken,
      params.id,
      body,
    );
    return json(result);
  } catch (err: unknown) {
    console.error("[Time] Failed to log time:", err);
    const status =
      err && typeof err === "object" && "status" in err
        ? (err as { status: number }).status
        : 500;
    const message =
      err && typeof err === "object" && "response" in err
        ? ((err as { response?: { data?: { message?: string } } }).response
            ?.data?.message ?? "Failed to log time")
        : "Failed to log time";
    throw error(status, message);
  }
};
