/**
 * DB-aware transactional email sender resolution.
 *
 * Resolution order (first match wins):
 *   1. `config.platform.email` — an explicit platform adapter keeps full
 *      control, matching the sync resolver's contract.
 *   2. Settings > Email (`__email_config__` document) via the provider factory
 *      registered by `@actuate-media/plugin-email`. Admin-entered settings
 *      beat env inference so what the UI shows is what actually sends.
 *   3. The env-configured sender registered at boot via `setEmailSender`.
 *
 * Lives apart from `sender.ts` so the lightweight `email-sender` subpath
 * (imported by plugin-email at config-load time) never drags in the DB or
 * crypto modules.
 */
import { getActuateConfig } from '../config/runtime.js';
import { getDB, isDBInitialized } from '../db.js';
import { getEmailProviderFactory, getRegisteredEmailSender } from './sender.js';
import { getEmailConfig, resolveEmailProviderSettings } from './settings-store.js';
// Built adapters are memoized on the config's updatedAt stamp so repeated
// sends don't rebuild providers (and SMTP doesn't re-verify) on every call.
// A single findFirst per send remains — acceptable for transactional volume.
let cache = null;
/** Test hook: drop the memoized DB-configured adapter. */
export function clearEmailSenderCache() {
    cache = null;
}
async function resolveDbConfiguredSender(db) {
    const factory = getEmailProviderFactory();
    if (!factory)
        return null;
    const client = db ?? (isDBInitialized() ? getDB() : null);
    if (!client)
        return null;
    const config = await getEmailConfig(client);
    if (!config.provider)
        return null;
    const stamp = `${config.provider}:${config.updatedAt ?? ''}`;
    if (cache && cache.stamp === stamp)
        return cache.adapter;
    const settings = await resolveEmailProviderSettings(config);
    const adapter = settings ? factory(settings) : null;
    cache = { stamp, adapter };
    return adapter;
}
/**
 * Resolve the active transactional email sender, checking the DB-backed
 * Settings > Email configuration. Returns `null` when nothing can send.
 *
 * Pass `db` when a client is already in hand (API routes); otherwise the
 * lazily-initialized module client is used.
 */
export async function resolveEmailSenderAsync(db) {
    const platform = getActuateConfig()?.platform?.email;
    if (platform)
        return platform;
    try {
        const dbSender = await resolveDbConfiguredSender(db);
        if (dbSender)
            return dbSender;
    }
    catch {
        // A broken DB config must never take down transactional email entirely —
        // fall through to the env-configured sender.
    }
    return getRegisteredEmailSender();
}
//# sourceMappingURL=resolve.js.map