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

export function createCreateTaskFromMailTool(client, options = {}) {
  const defaultBoardGroupId = options.defaultBoardGroupId || process.env.PRODUCTIER_BOARD_GROUP_ID_DEFAULT || "";
  const defaultWorkspaceSlug = options.defaultWorkspaceSlug || process.env.PRODUCTIER_WORKSPACE_SLUG_DEFAULT || "";

  return {
    name: "productier_create_task_from_mail",
    description: "Create a task from a mail message in Productier.",
    inputSchema: {
      type: "object",
      properties: {
        messageId: { type: "string" },
        boardGroupId: { type: "string", description: "Board group id. Defaults to PRODUCTIER_BOARD_GROUP_ID_DEFAULT." },
        title: { type: "string", description: "Optional custom task title." },
        dueAt: { type: "string", description: "Optional ISO date-time." },
        color: { type: "string", description: "Optional task color token." },
        workspaceSlug: { type: "string", description: "Optional workspace slug for output context only." }
      },
      required: ["messageId"],
      additionalProperties: false
    },
    async invoke(rawInput = {}) {
      const messageId = requireStringField(rawInput.messageId, "messageId");
      const boardGroupId = String(rawInput.boardGroupId || defaultBoardGroupId).trim();
      if (!boardGroupId) {
        throw new Error("boardGroupId is required (or set PRODUCTIER_BOARD_GROUP_ID_DEFAULT)");
      }

      const dueAt = optionalISODateTime(rawInput.dueAt, "dueAt");
      const title = optionalTrimmedString(rawInput.title);
      const color = optionalTrimmedString(rawInput.color);
      const body = {
        boardGroupId,
        ...(title ? { title } : {}),
        ...(dueAt ? { dueAt } : {}),
        ...(color ? { color } : {})
      };

      const response = await client.createTaskFromMail(messageId, body);
      return {
        created: true,
        sourceMessageId: messageId,
        workspaceSlug: resolveWorkspaceSlug(rawInput.workspaceSlug, defaultWorkspaceSlug) || null,
        task: response?.data ?? null
      };
    }
  };
}
