// services/queueService.js
const { SQSClient, SendMessageCommand } = require('@aws-sdk/client-sqs');
const config = require('../config');

class QueueService {
  constructor() {
    this.enabled = config.aws.sqs.enabled;
    this.sqsClient = null;
    
    if (this.enabled) {
      this.sqsClient = new SQSClient({ region: config.aws.region });
    }
  }

  async sendMessage(queueUrl, messageBody) {
    if (!this.enabled) {
      // In self-hosted mode, execute immediately
      console.log('Direct execution (no queue):', messageBody);
      await this._processMessageDirectly(messageBody);
      return;
    }
    
    try {
      const command = new SendMessageCommand({
        QueueUrl: queueUrl,
        MessageBody: JSON.stringify(messageBody)
      });
      
      await this.sqsClient.send(command);
    } catch (error) {
      console.error('Queue send error:', error);
      // Fallback to direct processing
      await this._processMessageDirectly(messageBody);
    }
  }

  async _processMessageDirectly(messageBody) {
    // Direct processing for self-hosted mode
    const emailService = require('./emailService');
    
    switch(messageBody.type) {
      case 'LOW_STOCK_ALERT':
        await emailService.sendLowStockAlert(messageBody);
        break;
      case 'ORDER_CONFIRMATION':
        await emailService.sendOrderConfirmation(messageBody);
        break;
      // Add other message types
    }
  }
}

const queueService = new QueueService();
module.exports = queueService;