'use strict'; const config = require('../../config/config'); const logger = require('../../utils/logger'); const { Setting, SETTINGS_KEY } = require('./settingModel'); const { isDbChannelEnabled, isEnvChannelEnabled, toPublicMessaging } = require('../../utils/messagingChannels'); let cache = null; let cacheAt = 0; const CACHE_TTL_MS = 10000; const readDbFlags = (doc) => ({ smsEnabled: doc?.smsEnabled, emailEnabled: doc?.emailEnabled, botEnabled: doc?.botEnabled }); const getDbMessagingFlags = async () => { const now = Date.now(); if (cache && (now - cacheAt) < CACHE_TTL_MS) return cache; const doc = await Setting.findOne({ key: SETTINGS_KEY }) .select('smsEnabled emailEnabled botEnabled') .lean(); cache = readDbFlags(doc); cacheAt = now; return cache; }; const invalidateMessagingCache = () => { cache = null; cacheAt = 0; }; const getMessagingChannelState = async (channel) => { const envEnabled = isEnvChannelEnabled(channel, config); if (!envEnabled) { return { enabled: false, envEnabled: false, dbEnabled: null, blockReason: 'env_disabled' }; } try { const db = await getDbMessagingFlags(); const dbEnabled = isDbChannelEnabled(channel, db); return { enabled: dbEnabled, envEnabled: true, dbEnabled, blockReason: dbEnabled ? null : 'dashboard_disabled' }; } catch (err) { logger.warn(`[Messaging] Failed to read settings for ${channel}, using env only: ${err.message}`); return { enabled: true, envEnabled: true, dbEnabled: null, blockReason: null }; } }; const isMessagingChannelEnabled = async (channel) => { const state = await getMessagingChannelState(channel); return state.enabled; }; const getPublicMessaging = (doc) => toPublicMessaging(readDbFlags(doc), config); module.exports = { getMessagingChannelState, isMessagingChannelEnabled, invalidateMessagingCache, getPublicMessaging, getDbMessagingFlags };