import GenericError from "../../../Errors/GenericError";
import { activityCw } from "./activities";
import { CWActivity, CWPatchOperation } from "./activity.types";

/**
 * Update an existing activity in ConnectWise using JSON Patch operations.
 *
 * @param cwActivityId - The ConnectWise activity ID to update
 * @param operations - Array of JSON Patch operations to apply
 * @returns The updated CW activity object
 * @throws GenericError if the update fails
 */
export const updateActivity = async (
  cwActivityId: number,
  operations: CWPatchOperation[],
): Promise<CWActivity> => {
  try {
    return await activityCw.update(cwActivityId, operations);
  } catch (error) {
    const errBody = (error as any).response?.data || error;
    console.error(`Error updating activity with ID ${cwActivityId}:`, errBody);
    throw new GenericError({
      name: "UpdateActivityError",
      message: `Failed to update activity ${cwActivityId}`,
      cause: typeof errBody === "string" ? errBody : JSON.stringify(errBody),
      status: 502,
    });
  }
};
