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

/** GET /sales/opportunity/[id]/workflow — fetch workflow status */
export const GET: RequestHandler = async ({ params, locals }) => {
  const accessToken = locals.session?.accessToken;
  if (!accessToken) throw error(401, "Unauthorized");

  try {
    const result = await optima.sales.fetchWorkflowStatus(
      accessToken,
      params.id,
    );
    return json(result);
  } catch (err: unknown) {
    console.error("[Workflow] Failed to fetch status:", 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 fetch workflow status")
        : "Failed to fetch workflow status";
    throw error(status, message);
  }
};

/** POST /sales/opportunity/[id]/workflow — dispatch workflow action */
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.action) throw error(400, "Action is required");

  try {
    const result = await optima.sales.dispatchWorkflowAction(
      accessToken,
      params.id,
      body.action,
      body.payload ?? {},
    );
    return json(result);
  } catch (err: unknown) {
    console.error("[Workflow] Action failed:", err);
    const status =
      err && typeof err === "object" && "status" in err
        ? (err as { status: number }).status
        : 500;

    // Extract the error response data for workflow failures
    let responseData: Record<string, unknown> | undefined;
    if (err && typeof err === "object" && "response" in err) {
      const axiosErr = err as {
        response?: { data?: Record<string, unknown>; status?: number };
      };
      responseData = axiosErr.response?.data;
    }

    // Return the full workflow error response so the UI can display it
    if (responseData) {
      return json(responseData, {
        status: (responseData.status as number) ?? status,
      });
    }

    throw error(status, "Workflow action failed");
  }
};
