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

/** POST /api/sales/opportunities — create an opportunity */
export const POST: RequestHandler = async ({ request, locals }) => {
  const accessToken = locals.session?.accessToken;
  if (!accessToken) throw error(401, "Unauthorized");

  const body = await request.json();
  if (!body.name?.trim()) throw error(400, "Name is required");
  if (!body.expectedCloseDate)
    throw error(400, "Expected close date is required");

  try {
    const result = await optima.sales.createOpportunity(accessToken, {
      name: body.name.trim(),
      expectedCloseDate: body.expectedCloseDate,
      notes: body.notes?.trim() || undefined,
      type: body.type || undefined,
      stage: body.stage || undefined,
      status: body.status || undefined,
      priority: body.priority || undefined,
      interest: body.interest || undefined,
      primarySalesRep: body.primarySalesRep || undefined,
      secondarySalesRep: body.secondarySalesRep || undefined,
      company: body.company || undefined,
      contact: body.contact || undefined,
      source: body.source || undefined,
      customerPO: body.customerPO || undefined,
    });
    return json(result, { status: 201 });
  } catch (err: unknown) {
    console.error("Failed to create opportunity:", 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 create opportunity"
        : "Failed to create opportunity";
    throw error(status, message);
  }
};
