import { getSession } from "./neo4j.js";
/**
 * Look up per-archive enrichment hints for a batch of IMAP messages.
 *
 * Given each message's RFC 5322 date, find an account-scoped
 * `:ConversationArchive {source:'email'}` whose `:Section` covers the
 * date. Returns at most one hint per message (the earliest matching
 * section by `firstMessageAt`).
 */
export async function getMessageArchiveHints(messages, accountId) {
    const out = new Map();
    const candidates = messages.filter((m) => !!m.messageId && !!m.receivedAt && !Number.isNaN(Date.parse(m.receivedAt)));
    if (candidates.length === 0)
        return out;
    const session = getSession();
    try {
        const result = await session.run(`UNWIND $msgs AS msg
       MATCH (a:ConversationArchive { accountId: $accountId, source: 'email' })
             -[:HAS_SECTION]->(s:Section)
       WHERE s.firstMessageAt IS NOT NULL
         AND s.lastMessageAt IS NOT NULL
         AND s.firstMessageAt <= msg.receivedAt
         AND s.lastMessageAt  >= msg.receivedAt
       WITH msg, a, s
       ORDER BY s.firstMessageAt ASC, coalesce(s.position, 0) ASC
       WITH msg.messageId AS messageId,
            collect({ archiveTitle: coalesce(a.title, ''),
                      sectionIndex: coalesce(s.position, 0) })[0] AS hint
       RETURN messageId, hint`, { msgs: candidates, accountId });
        for (const rec of result.records) {
            const messageId = rec.get("messageId");
            const hint = rec.get("hint");
            if (!hint)
                continue;
            const idxRaw = hint.sectionIndex;
            const sectionIndex = typeof idxRaw === "number"
                ? idxRaw
                : typeof idxRaw?.toNumber === "function"
                    ? idxRaw.toNumber()
                    : Number(idxRaw ?? 0);
            if (!hint.archiveTitle)
                continue;
            out.set(messageId, { archiveTitle: hint.archiveTitle, sectionIndex });
        }
    }
    finally {
        await session.close();
    }
    return out;
}
//# sourceMappingURL=conversation-archive-lookup.js.map