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

const allowedStatuses = new Set(["todo", "in_progress", "done"]);

export function createUpdateTaskTool(client) {
  return {
    name: "productier_update_task",
    description: "Update a Productier task.",
    inputSchema: {
      type: "object",
      properties: {
        taskId: { type: "string" },
        title: { type: "string" },
        description: { type: "string" },
        status: { type: "string", enum: ["todo", "in_progress", "done"] },
        boardGroupId: { type: "string" },
        color: { type: "string" },
        dueAt: { type: "string", description: "Optional ISO date-time string." },
        scheduledStart: { type: "string", description: "Optional ISO date-time string." },
        scheduledEnd: { type: "string", description: "Optional ISO date-time string." },
        assigneeId: { type: "string" }
      },
      required: ["taskId"],
      additionalProperties: false
    },
    async invoke(rawInput = {}) {
      const taskId = requireStringField(rawInput.taskId, "taskId");

      const status = rawInput.status ? String(rawInput.status).trim() : undefined;
      if (status && !allowedStatuses.has(status)) {
        throw new Error("status must be one of: todo, in_progress, done");
      }

      const update = {
        title: optionalString(rawInput.title),
        description: optionalString(rawInput.description),
        status,
        boardGroupId: optionalString(rawInput.boardGroupId),
        color: optionalString(rawInput.color),
        dueAt: optionalISODateTime(rawInput.dueAt, "dueAt"),
        scheduledStart: optionalISODateTime(rawInput.scheduledStart, "scheduledStart"),
        scheduledEnd: optionalISODateTime(rawInput.scheduledEnd, "scheduledEnd"),
        assigneeId: optionalString(rawInput.assigneeId)
      };

      const body = Object.fromEntries(Object.entries(update).filter(([, value]) => value !== undefined));
      ensureAtLeastOneField(body, "at least one field must be provided to update");

      const response = await client.updateTask(taskId, body);
      return {
        updated: true,
        task: response?.data ?? null
      };
    }
  };
}
