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

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

  try {
    const result = await optima.sales.fetchOpenActivities(
      accessToken,
      params.id,
    );
    return json(result);
  } catch (err: unknown) {
    console.error("[Activities] Failed to fetch:", err);
    const status =
      err && typeof err === "object" && "status" in err
        ? (err as { status: number }).status
        : 500;
    throw error(status, "Failed to fetch activities");
  }
};
