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

const DEFAULT_LIMIT = 200;
const MAX_LIMIT = 200;

function outgoingMatchesQuery(item, query) {
  if (!query) {
    return true;
  }

  const subject = String(item.subject || "").toLowerCase();
  const textBody = String(item.textBody || "").toLowerCase();
  const htmlBody = String(item.htmlBody || "").toLowerCase();
  const recipients = [...(item.to || []), ...(item.cc || []), ...(item.bcc || [])]
    .flatMap(address => [address?.name, address?.email])
    .filter(Boolean)
    .map(value => String(value).toLowerCase());
  return (
    subject.includes(query) ||
    textBody.includes(query) ||
    htmlBody.includes(query) ||
    recipients.some(value => value.includes(query))
  );
}

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

  return {
    name: "productier_list_outgoing_mails",
    description: "List outgoing mail queue items 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." },
        status: {
          type: "string",
          enum: ["all", "queued", "scheduled", "sent", "failed"],
          description: "Outgoing status filter, default all."
        },
        query: { type: "string", description: "Optional case-insensitive search over recipients and content." },
        limit: { type: "integer", minimum: 1, maximum: MAX_LIMIT, description: `Max outgoing records 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 status = rawInput.status ? String(rawInput.status).trim().toLowerCase() : "all";
      if (!["all", "queued", "scheduled", "sent", "failed"].includes(status)) {
        throw new Error("status must be one of: all, queued, scheduled, sent, failed");
      }
      const query = rawInput.query ? String(rawInput.query).trim().toLowerCase() : "";
      const limit = normalizeLimit(rawInput.limit, DEFAULT_LIMIT, MAX_LIMIT);

      const response = await client.listOutgoingMails(workspaceSlug, mailboxId);
      const outgoing = Array.isArray(response?.data) ? response.data : [];
      const filtered = outgoing
        .filter(item => (status === "all" ? true : String(item.status) === status))
        .filter(item => outgoingMatchesQuery(item, query))
        .slice(0, limit);

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