/**
 * EvolutionPollingService
 * 
 * Polls Evolution API for new messages since webhooks are not working
 * This is a temporary solution until webhookByEvents can be enabled
 */

const { logger } = require('../config/logger');
const EvolutionInstance = require('../models/EvolutionInstance');
const EvolutionAPIService = require('./EvolutionAPIService');
const eventBus = require('../core/whatsapp/EventBus');
const Events = require('../core/whatsapp/CoreEvents');

class EvolutionPollingService {
  constructor() {
    this.pollingIntervals = new Map();
    this.lastMessageTimestamps = new Map();
    this.isPolling = false;
  }

  /**
   * Start polling for all active Evolution instances
   */
  async startPolling(intervalMs = 5000) {
    if (this.isPolling) {
      logger.warn('Polling already started');
      return;
    }

    this.isPolling = true;
    logger.info('Starting Evolution API polling service', { intervalMs });

    // Poll every X seconds
    const pollInterval = setInterval(async () => {
      try {
        await this.pollAllInstances();
      } catch (error) {
        logger.error('Error in polling cycle', { error: error.message });
      }
    }, intervalMs);

    this.pollingIntervals.set('main', pollInterval);
  }

  /**
   * Stop polling
   */
  stopPolling() {
    this.pollingIntervals.forEach((interval) => {
      clearInterval(interval);
    });
    this.pollingIntervals.clear();
    this.isPolling = false;
    logger.info('Evolution API polling service stopped');
  }

  /**
   * Poll all active instances for new messages
   */
  async pollAllInstances() {
    try {
      // Get all connected Evolution instances
      const instances = await EvolutionInstance.getAllActive();

      for (const instance of instances) {
        try {
          await this.pollInstance(instance);
        } catch (error) {
          logger.error('Error polling instance', {
            instanceId: instance.id,
            error: error.message
          });
        }
      }
    } catch (error) {
      logger.error('Error getting active instances', { error: error.message });
    }
  }

  /**
   * Poll a single instance for new messages
   */
  async pollInstance(instance) {
    // Implementation will fetch messages from Evolution API
    // and emit them to the event bus
    logger.debug('Polling instance', { instanceId: instance.id });
    
    // TODO: Implement actual polling logic
    // This would call Evolution API to get recent messages
    // and compare with lastMessageTimestamps to find new ones
  }
}

module.exports = new EvolutionPollingService();
