import { loadCredentials } from "../lib/credentials.js";
import { searchMessages, MAX_LIMIT } from "../lib/imap.js";
import { getThreadInfo, stripAngleBrackets } from "../lib/graph.js";
export async function emailSearch(params) {
    const result = await loadCredentials(params.accountId);
    if ("error" in result)
        throw new Error(result.error);
    const { config, password } = result.credentials;
    // Clamp limit to hard cap — silently, per spec
    const requestedLimit = Math.max(1, params.limit ?? 20);
    const limit = Math.min(requestedLimit, MAX_LIMIT);
    // Use agent address for TO filtering when alias is configured
    // Coerce empty string to undefined to avoid matching nothing silently
    const to = (params.to || undefined) ?? (config.agentAddress !== config.email ? config.agentAddress : undefined);
    const { messages, nextBeforeUid } = await searchMessages(config, password, {
        sender: params.sender,
        subject: params.subject,
        body: params.body,
        since: params.since ? new Date(params.since) : undefined,
        before: params.before ? new Date(params.before) : undefined,
        limit,
        to,
        folder: params.folder,
        beforeUid: params.before_uid,
    });
    if (messages.length === 0) {
        return "No messages match the search criteria.";
    }
    // Enrich with thread info from the graph (best-effort — failures return empty map)
    const messageIds = messages.map((m) => m.messageId).filter((id) => !!id);
    let threadMap = new Map();
    try {
        threadMap = await getThreadInfo(messageIds, params.accountId);
    }
    catch {
        // Thread enrichment is optional — continue without it
    }
    const lines = messages
        .map((m) => {
        let entry = `UID: ${m.uid}\nFrom: ${m.from}\nSubject: ${m.subject}\nDate: ${m.date}`;
        if (m.messageId)
            entry += `\nMessage-ID: ${m.messageId}`;
        if (m.inReplyTo)
            entry += `\nIn-Reply-To: ${m.inReplyTo}`;
        const normalisedMid = stripAngleBrackets(m.messageId);
        if (normalisedMid) {
            const thread = threadMap.get(normalisedMid);
            if (thread) {
                entry += `\nThread-Depth: ${thread.threadDepth}`;
                entry += `\nThread-ID: ${thread.threadId}`;
            }
        }
        if (m.bodyPreview)
            entry += `\n\n${m.bodyPreview}`;
        return entry + "\n---";
    })
        .join("\n\n");
    if (nextBeforeUid) {
        return `${lines}\n\nPagination: next_before_uid=${nextBeforeUid} (pass as before_uid to get older messages)`;
    }
    return lines;
}
//# sourceMappingURL=email-search.js.map