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

const DEFAULT_LIMIT = 100;
const MAX_LIMIT = 200;

function mailboxMatchesQuery(mailbox, query) {
  if (!query) {
    return true;
  }

  const label = String(mailbox.label || "").toLowerCase();
  const email = String(mailbox.email || "").toLowerCase();
  const displayName = String(mailbox.displayName || "").toLowerCase();
  const imapHost = String(mailbox.imapHost || "").toLowerCase();
  const smtpHost = String(mailbox.smtpHost || "").toLowerCase();
  const syncError = String(mailbox.syncError || "").toLowerCase();
  return (
    label.includes(query) ||
    email.includes(query) ||
    displayName.includes(query) ||
    imapHost.includes(query) ||
    smtpHost.includes(query) ||
    syncError.includes(query)
  );
}

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

  return {
    name: "productier_list_mailboxes",
    description: "List connected mailboxes 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 search over mailbox fields." },
        syncStatus: {
          type: "string",
          enum: ["all", "idle", "syncing", "ready", "error"],
          description: "Sync status filter, default all."
        },
        limit: { type: "integer", minimum: 1, maximum: MAX_LIMIT, description: `Max mailboxes 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 syncStatus = rawInput.syncStatus ? String(rawInput.syncStatus).trim().toLowerCase() : "all";
      if (!["all", "idle", "syncing", "ready", "error"].includes(syncStatus)) {
        throw new Error("syncStatus must be one of: all, idle, syncing, ready, error");
      }
      const limit = normalizeLimit(rawInput.limit, DEFAULT_LIMIT, MAX_LIMIT);

      const response = await client.listMailboxes(workspaceSlug);
      const mailboxes = Array.isArray(response?.data) ? response.data : [];
      const filtered = mailboxes
        .filter(mailbox => (syncStatus === "all" ? true : String(mailbox.syncStatus) === syncStatus))
        .filter(mailbox => mailboxMatchesQuery(mailbox, query))
        .slice(0, limit);

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