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

const DEFAULT_LIMIT = 200;
const MAX_LIMIT = 200;

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

  return {
    name: "productier_list_calendar_events",
    description: "List calendar events for a Productier workspace.",
    inputSchema: {
      type: "object",
      properties: {
        workspaceSlug: { type: "string", description: "Workspace slug. Defaults to PRODUCTIER_WORKSPACE_SLUG_DEFAULT." },
        query: { type: "string", description: "Optional case-insensitive title/description filter." },
        from: { type: "string", description: "Optional ISO date-time lower bound for startsAt." },
        to: { type: "string", description: "Optional ISO date-time upper bound for startsAt." },
        limit: { type: "integer", minimum: 1, maximum: MAX_LIMIT, description: `Max events returned, default ${DEFAULT_LIMIT}.` }
      },
      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 query = rawInput.query ? String(rawInput.query).trim().toLowerCase() : "";
      const from = optionalISODateTime(rawInput.from, "from");
      const to = optionalISODateTime(rawInput.to, "to");
      const fromMs = from ? new Date(from).getTime() : undefined;
      const toMs = to ? new Date(to).getTime() : undefined;
      const limit = normalizeLimit(rawInput.limit, DEFAULT_LIMIT, MAX_LIMIT);

      const response = await client.listCalendarEvents(workspaceSlug);
      const events = Array.isArray(response?.data) ? response.data : [];
      const filtered = events
        .filter(event => {
          if (!query) {
            return true;
          }
          const title = String(event.title || "").toLowerCase();
          const description = String(event.description || "").toLowerCase();
          return title.includes(query) || description.includes(query);
        })
        .filter(event => {
          if (!fromMs && !toMs) {
            return true;
          }
          const startsMs = new Date(String(event.startsAt || "")).getTime();
          if (Number.isNaN(startsMs)) {
            return false;
          }
          if (fromMs && startsMs < fromMs) {
            return false;
          }
          if (toMs && startsMs > toMs) {
            return false;
          }
          return true;
        })
        .slice(0, limit);

      return {
        workspaceSlug,
        count: filtered.length,
        truncated: events.length > filtered.length,
        events: filtered
      };
    }
  };
}
