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

const DEFAULT_LIMIT = 200;
const MAX_LIMIT = 200;

function messageMatchesQuery(message, query) {
  if (!query) {
    return true;
  }

  const subject = String(message.subject || "").toLowerCase();
  const snippet = String(message.snippet || "").toLowerCase();
  const textBody = String(message.textBody || "").toLowerCase();
  const fromName = String(message.from?.name || "").toLowerCase();
  const fromEmail = String(message.from?.email || "").toLowerCase();
  return (
    subject.includes(query) ||
    snippet.includes(query) ||
    textBody.includes(query) ||
    fromName.includes(query) ||
    fromEmail.includes(query)
  );
}

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

  return {
    name: "productier_list_mail_messages",
    description: "List mail messages for a Productier workspace and optional mailbox.",
    inputSchema: {
      type: "object",
      properties: {
        workspaceSlug: { type: "string", description: "Workspace slug. Defaults to PRODUCTIER_WORKSPACE_SLUG_DEFAULT." },
        mailboxId: { type: "string", description: "Optional mailbox filter." },
        query: { type: "string", description: "Optional case-insensitive search over sender/subject/snippet/body." },
        unreadOnly: { type: "boolean", description: "When true, return only unread messages." },
        linked: { type: "string", enum: ["all", "linked", "unlinked"], description: "Task-link filter, default all." },
        limit: { type: "integer", minimum: 1, maximum: MAX_LIMIT, description: `Max messages 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 mailboxId = rawInput.mailboxId ? String(rawInput.mailboxId).trim() : undefined;
      const query = rawInput.query ? String(rawInput.query).trim().toLowerCase() : "";
      const unreadOnly = rawInput.unreadOnly === true;
      const linked = rawInput.linked ? String(rawInput.linked).trim() : "all";
      if (linked !== "all" && linked !== "linked" && linked !== "unlinked") {
        throw new Error("linked must be one of: all, linked, unlinked");
      }
      const limit = normalizeLimit(rawInput.limit, DEFAULT_LIMIT, MAX_LIMIT);

      const response = await client.listMailMessages(workspaceSlug, mailboxId);
      const messages = Array.isArray(response?.data) ? response.data : [];
      const filtered = messages
        .filter(message => (unreadOnly ? message.isRead === false : true))
        .filter(message => {
          if (linked === "all") {
            return true;
          }
          if (linked === "linked") {
            return Boolean(message.linkedTaskId);
          }
          return !message.linkedTaskId;
        })
        .filter(message => messageMatchesQuery(message, query))
        .slice(0, limit);

      return {
        workspaceSlug,
        mailboxId: mailboxId || null,
        count: filtered.length,
        truncated: messages.length > filtered.length,
        messages: filtered
      };
    }
  };
}
