import { ensureAtLeastOneField, requireStringField } from "./tool-helpers.mjs";

function optionalInteger(rawValue, fieldName) {
  if (rawValue === undefined) {
    return undefined;
  }
  const parsed = Number.parseInt(String(rawValue), 10);
  if (Number.isNaN(parsed)) {
    throw new Error(`${fieldName} must be an integer`);
  }
  return parsed;
}

export function createUpdateBoardGroupTool(client) {
  return {
    name: "productier_update_board_group",
    description: "Update a Productier board group.",
    inputSchema: {
      type: "object",
      properties: {
        groupId: { type: "string" },
        name: { type: "string" },
        color: { type: "string" },
        order: { type: "integer" }
      },
      required: ["groupId"],
      additionalProperties: false
    },
    async invoke(rawInput = {}) {
      const groupId = requireStringField(rawInput.groupId, "groupId");
      const body = Object.fromEntries(
        Object.entries({
          name: rawInput.name === undefined ? undefined : String(rawInput.name),
          color: rawInput.color === undefined ? undefined : String(rawInput.color),
          order: optionalInteger(rawInput.order, "order")
        }).filter(([, value]) => value !== undefined),
      );
      ensureAtLeastOneField(body, "at least one field must be provided to update");

      const response = await client.updateBoardGroup(groupId, body);
      return {
        updated: true,
        boardGroup: response?.data ?? null
      };
    }
  };
}
