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

export function createUpdateCalendarEventTool(client) {
  return {
    name: "productier_update_calendar_event",
    description: "Update a Productier calendar event.",
    inputSchema: {
      type: "object",
      properties: {
        eventId: { type: "string" },
        title: { type: "string" },
        description: { type: "string" },
        startsAt: { type: "string", description: "Optional ISO date-time." },
        endsAt: { type: "string", description: "Optional ISO date-time." },
        linkedTaskId: { type: "string" },
        color: { type: "string" }
      },
      required: ["eventId"],
      additionalProperties: false
    },
    async invoke(rawInput = {}) {
      const eventId = requireStringField(rawInput.eventId, "eventId");
      const startsAt = optionalISODateTime(rawInput.startsAt, "startsAt");
      const endsAt = optionalISODateTime(rawInput.endsAt, "endsAt");

      if (startsAt && endsAt && new Date(endsAt).getTime() < new Date(startsAt).getTime()) {
        throw new Error("endsAt must be greater than or equal to startsAt");
      }

      const body = Object.fromEntries(
        Object.entries({
          title: optionalString(rawInput.title),
          description: optionalString(rawInput.description),
          startsAt,
          endsAt,
          linkedTaskId: optionalTrimmedString(rawInput.linkedTaskId),
          color: optionalTrimmedString(rawInput.color)
        }).filter(([, value]) => value !== undefined),
      );
      ensureAtLeastOneField(body, "at least one field must be provided to update");

      const response = await client.updateCalendarEvent(eventId, body);
      return {
        updated: true,
        event: response?.data ?? null
      };
    }
  };
}
