const { pool, query } = require('./db');
const config = require('./config');
const notificationService = require('./services/notificationService');
const queueService = require('./services/queueService');
const { Consumer } = require('sqs-consumer');
const { SQSClient } = require('@aws-sdk/client-sqs');

console.log('Starting worker process...');
console.log(`Environment: ${process.env.ENVIRONMENT || 'beta'}`);
console.log(`Deployment mode: ${process.env.DEPLOYMENT_MODE || 'self-hosted'}`);

// Worker initialization
async function initWorker() {
  try {
    await pool.connect();
    console.log('Worker connected to database');
    
    // Set up processing intervals for database-based notifications
    const interval = process.env.ENVIRONMENT === 'prod' ? 10 * 60 * 1000 : 2 * 60 * 1000;
    
    setInterval(async () => {
      try {
        console.log('Processing low stock notifications...');
        const processedCount = await notificationService.processLowStockNotifications(pool, query);
        console.log(`Processed ${processedCount} low stock notifications`);
      } catch (error) {
        console.error('Error processing low stock notifications:', error);
      }
    }, interval);
    
    // For cloud mode, add SQS message consumption here
    if (config.aws && config.aws.sqs && config.aws.sqs.enabled && config.aws.sqs.queueUrl) {
      console.log(`Starting SQS consumer for queue: ${config.aws.sqs.queueUrl}`);
      
      // Create SQS consumer
      const consumer = Consumer.create({
        queueUrl: config.aws.sqs.queueUrl,
        handleMessage: async (message) => {
          try {
            console.log('Processing SQS message:', message.MessageId);
            const messageBody = JSON.parse(message.Body);
            
            // Use the direct processing method from queueService
            await queueService._processMessageDirectly(messageBody);
            
            console.log('Successfully processed message:', message.MessageId);
          } catch (error) {
            console.error('Error processing message:', message.MessageId, error);
            throw error; // Rethrow to handle message as failed
          }
        },
        sqs: new SQSClient({ region: config.aws.region }),
        batchSize: 10,
        visibilityTimeout: 60,
        waitTimeSeconds: 20
      });
      
      consumer.on('error', (err) => {
        console.error('SQS consumer error:', err.message);
      });
      
      consumer.on('processing_error', (err) => {
        console.error('SQS message processing error:', err.message);
      });
      
      consumer.start();
      console.log('SQS consumer started');
    }
    
  } catch (error) {
    console.error('Worker initialization error:', error);
    process.exit(1);
  }
}

// Start the worker
initWorker().catch(err => {
  console.error('Unhandled worker error:', err);
  process.exit(1);
});

// Handle graceful shutdown
process.on('SIGTERM', async () => {
  console.log('Worker received SIGTERM, shutting down gracefully');
  await pool.end();
  process.exit(0);
});

process.on('SIGINT', async () => {
  console.log('Worker received SIGINT, shutting down gracefully');
  await pool.end();
  process.exit(0);
});