const eventBus = require('../../core/whatsapp/EventBus');
const Events = require('../../core/whatsapp/CoreEvents');
const { safeExecute } = require('../../core/whatsapp/SafeExecute');
const { logInfo } = require('../../core/whatsapp/LogContext');
const { CloudFlowService } = require('../../services/whatsapp/CloudFlowService');
const WhatsAppCloudFAQService = require('../../services/WhatsAppCloudFAQService');

class CloudMessageModule {
  register() {
    eventBus.on(Events.MESSAGE_RECEIVED, (payload) => {
      if (payload.channel !== 'cloud') return;
      const context = {
        tenant_id: payload.tenantId,
        session_id: payload.sessionId || null,
        message_id: payload.messageId || null,
        module: 'cloud_message_module',
        event: 'message_received',
        step: 'dispatch'
      };
      safeExecute(() => this.handle(payload), context);
    });
  }

  async handle(payload) {
    logInfo('Cloud message handling started', {
      tenant_id: payload.tenantId,
      session_id: payload.sessionId || null,
      module: 'cloud_message_module',
      event: 'message_received',
      step: 'handle'
    });

    if (payload.flowContext) {
      await safeExecute(
        () => CloudFlowService.processFlowAutoReply(payload.flowContext),
        {
          tenant_id: payload.tenantId,
          session_id: payload.sessionId || null,
          message_id: payload.messageId || null,
          module: 'cloud_flow_module',
          event: 'message_received',
          step: 'process_flow'
        }
      );
    }

    if (payload.enableFaq) {
      await safeExecute(
        () => WhatsAppCloudFAQService.processMessage(
          payload.tenantId,
          payload.accountId,
          payload.conversationId,
          payload.textBody || '',
          payload.contactPhone,
          { contactName: payload.contactName, messageType: payload.messageType }
        ),
        {
          tenant_id: payload.tenantId,
          session_id: payload.sessionId || null,
          message_id: payload.messageId || null,
          module: 'cloud_faq_module',
          event: 'message_received',
          step: 'process_faq'
        }
      );
    }
  }
}

module.exports = { CloudMessageModule };
