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

const DEFAULT_LIMIT = 200;
const MAX_LIMIT = 200;

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

  return {
    name: "productier_list_notes",
    description: "List notes 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/content filter." },
        limit: { type: "integer", minimum: 1, maximum: MAX_LIMIT, description: `Max notes 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 limit = normalizeLimit(rawInput.limit, DEFAULT_LIMIT, MAX_LIMIT);
      const response = await client.listNotes(workspaceSlug);
      const notes = Array.isArray(response?.data) ? response.data : [];
      const filtered = notes
        .filter(note => {
          if (!query) {
            return true;
          }
          const title = String(note.title || "").toLowerCase();
          const content = String(note.content || "").toLowerCase();
          return title.includes(query) || content.includes(query);
        })
        .slice(0, limit);

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