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

const MAX_LIMIT = 200;
const DEFAULT_LIMIT = 50;

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

  return {
    name: "productier_list_tasks",
    description: "List tasks from a Productier workspace with optional status/text filtering.",
    inputSchema: {
      type: "object",
      properties: {
        workspaceSlug: { type: "string", description: "Workspace slug. Defaults to PRODUCTIER_WORKSPACE_SLUG_DEFAULT." },
        status: { type: "string", description: "Optional status filter (for example todo, in_progress, done)." },
        query: { type: "string", description: "Optional case-insensitive text filter over title and description." },
        limit: { type: "integer", minimum: 1, maximum: MAX_LIMIT, description: `Max tasks 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 limit = normalizeLimit(rawInput.limit, DEFAULT_LIMIT, MAX_LIMIT);
      const statusFilter = rawInput.status ? String(rawInput.status).trim().toLowerCase() : "";
      const query = rawInput.query ? String(rawInput.query).trim().toLowerCase() : "";

      const response = await client.listTasks(workspaceSlug);
      const tasks = Array.isArray(response?.data) ? response.data : [];

      const matched = tasks
        .filter(task => (statusFilter ? String(task.status || "").toLowerCase() === statusFilter : true))
        .filter(task => {
          if (!query) {
            return true;
          }
          const title = String(task.title || "").toLowerCase();
          const description = String(task.description || "").toLowerCase();
          return title.includes(query) || description.includes(query);
        });

      const filtered = matched.slice(0, limit);

      return {
        workspaceSlug,
        count: filtered.length,
        truncated: matched.length > limit,
        tasks: filtered
      };
    }
  };
}
