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

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

  return {
    name: "productier_create_calendar_event",
    description: "Create a Productier calendar event.",
    inputSchema: {
      type: "object",
      properties: {
        workspaceSlug: { type: "string", description: "Workspace slug. Defaults to PRODUCTIER_WORKSPACE_SLUG_DEFAULT." },
        title: { type: "string" },
        description: { type: "string" },
        startsAt: { type: "string", description: "ISO date-time." },
        endsAt: { type: "string", description: "ISO date-time." },
        linkedTaskId: { type: "string" },
        color: { type: "string" }
      },
      required: ["title", "startsAt", "endsAt"],
      additionalProperties: false
    },
    async invoke(rawInput = {}) {
      const workspaceSlug = resolveWorkspaceSlug(rawInput.workspaceSlug, defaultWorkspaceSlug);
      if (!workspaceSlug) {
        throw new Error("workspaceSlug is required (or set PRODUCTIER_WORKSPACE_SLUG_DEFAULT)");
      }

      const title = requireStringField(rawInput.title, "title");
      const startsAt = optionalISODateTime(requireStringField(rawInput.startsAt, "startsAt"), "startsAt");
      const endsAt = optionalISODateTime(requireStringField(rawInput.endsAt, "endsAt"), "endsAt");

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

      const linkedTaskId = optionalTrimmedString(rawInput.linkedTaskId);
      const color = optionalTrimmedString(rawInput.color);
      const body = {
        workspaceSlug,
        title,
        description: rawInput.description === undefined ? "" : String(rawInput.description),
        startsAt,
        endsAt,
        ...(linkedTaskId ? { linkedTaskId } : {}),
        ...(color ? { color } : {})
      };

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