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

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

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

  return {
    name: "productier_create_task",
    description: "Create a task in a Productier workspace.",
    inputSchema: {
      type: "object",
      properties: {
        workspaceSlug: { type: "string", description: "Workspace slug. Defaults to PRODUCTIER_WORKSPACE_SLUG_DEFAULT." },
        boardGroupId: { type: "string", description: "Board group id. Defaults to PRODUCTIER_BOARD_GROUP_ID_DEFAULT." },
        title: { type: "string" },
        description: { type: "string" },
        color: { type: "string", description: "Task color token. Defaults to slate." },
        dueAt: { type: "string", description: "Optional ISO date-time string." }
      },
      required: ["title"],
      additionalProperties: false
    },
    async invoke(rawInput = {}) {
      const workspaceSlug = resolveWorkspaceSlug(rawInput.workspaceSlug, defaultWorkspaceSlug);
      const boardGroupId = resolveWorkspaceSlug(rawInput.boardGroupId, defaultBoardGroupID);
      const title = requireStringField(rawInput.title, "title");

      if (!workspaceSlug) {
        throw new Error("workspaceSlug is required (or set PRODUCTIER_WORKSPACE_SLUG_DEFAULT)");
      }
      if (!boardGroupId) {
        throw new Error("boardGroupId is required (or set PRODUCTIER_BOARD_GROUP_ID_DEFAULT)");
      }

      const dueAt = optionalISODateTime(rawInput.dueAt, "dueAt");
      const body = {
        workspaceSlug,
        boardGroupId,
        title,
        description: rawInput.description ? String(rawInput.description) : "",
        color: rawInput.color ? String(rawInput.color) : "slate",
        ...(dueAt ? { dueAt } : {})
      };

      const response = await client.createTask(body);
      const task = response?.data ?? null;

      if (task?.status && !allowedStatuses.has(String(task.status))) {
        throw new Error(`unexpected task status from API: ${task.status}`);
      }

      return {
        created: task !== null,
        task
      };
    }
  };
}
