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

const DEFAULT_LIMIT = 200;
const MAX_LIMIT = 200;

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

  return {
    name: "productier_list_board_groups",
    description: "List board groups 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 name filter." },
        color: { type: "string", description: "Optional color filter." },
        limit: { type: "integer", minimum: 1, maximum: MAX_LIMIT, description: `Max groups 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 color = rawInput.color ? String(rawInput.color).trim().toLowerCase() : "";
      const limit = normalizeLimit(rawInput.limit, DEFAULT_LIMIT, MAX_LIMIT);

      const response = await client.listBoardGroups(workspaceSlug);
      const groups = Array.isArray(response?.data) ? response.data : [];
      const filtered = groups
        .filter(group => (query ? String(group.name || "").toLowerCase().includes(query) : true))
        .filter(group => (color ? String(group.color || "").toLowerCase() === color : true))
        .slice(0, limit);

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