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

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

  const type = url.searchParams.get("type") ?? undefined;

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