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

class WebMessageModule {
  constructor(whatsappService) {
    this.whatsappService = whatsappService;
  }

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

  async handle(payload) {
    const instance = this.whatsappService?.getInstance?.(payload.tenantId);
    if (!instance?.messageHandler) {
      logWarn('Web message handler not available', {
        tenant_id: payload.tenantId,
        module: 'web_message_module',
        event: 'message_received',
        step: 'resolve_handler'
      });
      return;
    }
    logInfo('Web message handling started', {
      tenant_id: payload.tenantId,
      module: 'web_message_module',
      event: 'message_received',
      step: 'handle'
    });
    await instance.messageHandler.handleMessage(
      payload.tenantId,
      payload.upsert,
      payload.sock,
      payload.downloadMediaMessage
    );
  }
}

module.exports = { WebMessageModule };
