import { callGraph } from "../lib/graph-client.js";
import { log, trunc } from "../lib/log.js";
const FIELDS = "id,subject,from,receivedDateTime,bodyPreview,isRead";
export async function runMailSearch(config, args) {
    const top = clampTop(args.top, 25);
    const query = args.query.trim();
    if (!query) {
        throw new Error("mail-search: query is required and must be non-empty.");
    }
    const startMs = Date.now();
    const result = await callGraph(config, async (client) => {
        // Graph requires the $search value to be enclosed in quotes.
        return (await client
            .api("/me/messages")
            .search(`"${query.replace(/"/g, '\\"')}"`)
            .top(top)
            .select(FIELDS)
            // ConsistencyLevel header is required for $search. Older SDK shapes
            // accept .header; newer shapes expose it via .request().
            .header("ConsistencyLevel", "eventual")
            .get());
    }, { tool: "mail-search" });
    const items = result.value.map((msg) => ({
        id: msg.id,
        subject: msg.subject ?? null,
        from: msg.from?.emailAddress?.address ?? null,
        receivedDateTime: msg.receivedDateTime,
        bodyPreview: (msg.bodyPreview ?? "").slice(0, 1024),
        isRead: msg.isRead ?? false,
    }));
    log({
        event: "mail-search",
        account: config.accountId,
        query: trunc(query, 32),
        count: items.length,
        elapsedMs: Date.now() - startMs,
    });
    return items;
}
function clampTop(input, fallback) {
    if (typeof input !== "number" || !Number.isFinite(input))
        return fallback;
    if (input < 1)
        return 1;
    if (input > 250)
        return 250;
    return Math.floor(input);
}
//# sourceMappingURL=mail-search.js.map