import { callGraph } from "../lib/graph-client.js";
import { log } from "../lib/log.js";
const FIELDS = "id,subject,from,receivedDateTime,bodyPreview,isRead";
export async function runMailList(config, args) {
    const top = clampTop(args.top, 25);
    const folder = args.folder ?? "Inbox";
    const startMs = Date.now();
    const result = await callGraph(config, async (client) => {
        const path = folder.toLowerCase() === "inbox" || folder === ""
            ? "/me/mailFolders/Inbox/messages"
            : `/me/mailFolders/${encodeURIComponent(folder)}/messages`;
        return (await client
            .api(path)
            .top(top)
            .orderby("receivedDateTime DESC")
            .select(FIELDS)
            .get());
    }, { tool: "mail-list" });
    const items = result.value.map(shapeMessage);
    log({
        event: "mail-list",
        account: config.accountId,
        folder,
        count: items.length,
        elapsedMs: Date.now() - startMs,
    });
    return items;
}
function shapeMessage(msg) {
    return {
        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,
    };
}
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-list.js.map