const config = require('../config');
const emailService = require('./emailService');

/**
 * Service for handling notifications including stock alerts
 */
const notificationService = {
  /**
   * Process pending low stock notifications
   * @param {Object} pool - Database connection pool
   * @param {Function} query - Database query function
   * @returns {Promise<number>} Number of notifications processed
   */
  async processLowStockNotifications(pool, query) {
    const client = await pool.connect();
    let processedCount = 0;
    
    try {
      await client.query('BEGIN');
      
      // Get pending low stock notifications
      const pendingNotifications = await client.query(`
        SELECT id 
        FROM notification_logs 
        WHERE notification_type = 'low_stock_alert' 
        AND status = 'pending'
        LIMIT 50
      `);
      
      if (pendingNotifications.rows.length === 0) {
        await client.query('COMMIT');
        return 0;
      }
      
      // Get products with current stock below threshold
      const lowStockProducts = await client.query(`
        SELECT 
          p.id, 
          p.name, 
          p.stock_quantity, 
          p.stock_notification 
        FROM products p
        WHERE 
          p.stock_notification IS NOT NULL 
          AND p.stock_notification->>'enabled' = 'true'
          AND p.stock_notification->>'email' IS NOT NULL
          AND p.stock_quantity <= (p.stock_notification->>'threshold')::int
      `);
      
      if (lowStockProducts.rows.length === 0) {
        // Mark notifications as processed with no action
        const notificationIds = pendingNotifications.rows.map(n => n.id);
        await client.query(`
          UPDATE notification_logs
          SET status = 'completed', error_message = 'No eligible products found'
          WHERE id = ANY($1)
        `, [notificationIds]);
        
        await client.query('COMMIT');
        return 0;
      }
      
      // Send notifications for each low stock product
      for (const product of lowStockProducts.rows) {
        console.log("LOW STOCK ON: ", JSON.stringify(product, null, 4))
        const notification = product.stock_notification;
        
        try {
          // Send email notification using template
          await emailService.sendLowStockAlert({
            to: notification.email,
            product_name: product.name,
            current_stock: product.stock_quantity.toString(),
            threshold: notification.threshold.toString()
          });
          
          // Mark one notification as processed
          if (pendingNotifications.rows[processedCount]) {
            await client.query(`
              UPDATE notification_logs
              SET status = 'success'
              WHERE id = $1
            `, [pendingNotifications.rows[processedCount].id]);
            
            processedCount++;
          }
        } catch (error) {
          console.error(`Error sending low stock notification for product ${product.id}:`, error);
          
          // Mark notification as failed
          if (pendingNotifications.rows[processedCount]) {
            await client.query(`
              UPDATE notification_logs
              SET status = 'failed', error_message = $2
              WHERE id = $1
            `, [pendingNotifications.rows[processedCount].id, error.message]);
            
            processedCount++;
          }
        }
      }
      
      await client.query('COMMIT');
      return processedCount;
    } catch (error) {
      await client.query('ROLLBACK');
      console.error('Error processing low stock notifications:', error);
      throw error;
    } finally {
      client.release();
    }
  }
};

module.exports = notificationService;