const PrintedData = require('../models/PrintedData');

// Get all printed data
exports.getAllPrintedData = async (req, res) => {
  try {
    // Fetch all printed data, sorted by createdAt (newest first)
    const printedData = await PrintedData.find()
      .sort({ createdAt: -1 })
      .populate('orderId', 'orderNo tableNo')
      .lean();

    res.status(200).json({
      success: true,
      data: printedData
    });
  } catch (error) {
    console.error('Error fetching printed data:', error);
    res.status(500).json({
      success: false,
      message: 'Error fetching printed data',
      error: error.message
    });
  }
};

// Save print data separately - stores only the printed data for audit/history
exports.savePrintData = async (req, res) => {
  try {
    const { orderId, orderNo, tableNo, waiterName, changes, items, printType } = req.body;

    // Validate required fields
    if (!orderId || !orderNo) {
      return res.status(400).json({ 
        success: false, 
        message: 'Missing required fields: orderId and orderNo are required' 
      });
    }

    // Determine print type (new_order or order_update)
    const isNewOrder = printType === 'new_order' || (!changes && items);
    
    let printData;
    
    if (isNewOrder) {
      // For new orders, all items go into addedItems
      if (!items || items.length === 0) {
        return res.status(400).json({ 
          success: false, 
          message: 'No items to save - print data must contain at least one item' 
        });
      }

      printData = new PrintedData({
        orderId: orderId,
        orderNo: orderNo,
        tableNo: tableNo || null,
        waiterName: waiterName || 'N/A',
        printType: 'new_order',
        addedItems: items.map(item => ({
          itemId: item.itemId || null,
          itemName: item.name || item.itemName || 'Unknown',
          quantity: item.quantity || 0,
          specialNeeds: item.specialNeeds || []
        })),
        quantityChanged: [],
        removedItems: []
      });
    } else {
      // For order updates, use changes structure
      if (!changes || (!changes.added?.length && !changes.removed?.length && !changes.quantityChanged?.length)) {
        return res.status(400).json({ 
          success: false, 
          message: 'No changes to save - print data must contain at least one change' 
        });
      }

      // Calculate quantityChange for quantityChanged items
      const quantityChangedWithDelta = (changes.quantityChanged || []).map(item => ({
        ...item,
        quantityChange: item.currentQuantity - item.previousQuantity
      }));

      printData = new PrintedData({
        orderId: orderId,
        orderNo: orderNo,
        tableNo: tableNo || null,
        waiterName: waiterName || 'N/A',
        printType: 'order_update',
        addedItems: (changes.added || []).map(item => ({
          itemId: item.itemId || null,
          itemName: item.itemName || 'Unknown',
          quantity: item.quantity || 0,
          specialNeeds: item.specialNeeds || []
        })),
        quantityChanged: quantityChangedWithDelta.map(item => ({
          itemId: item.itemId || null,
          itemName: item.itemName || 'Unknown',
          previousQuantity: item.previousQuantity || 0,
          currentQuantity: item.currentQuantity || 0,
          quantityChange: item.quantityChange || 0,
          specialNeeds: item.specialNeeds || []
        })),
        removedItems: (changes.removed || []).map(item => ({
          itemId: item.itemId || null,
          itemName: item.itemName || 'Unknown',
          quantity: item.quantity || 0,
          specialNeeds: item.specialNeeds || []
        }))
      });
    }

    await printData.save();

    // Broadcast print data to all connected clients via Socket.IO
    if (global.io) {
      const printDataForSocket = {
        orderId: orderId,
        orderNo: orderNo,
        tableNo: tableNo || null,
        waiterName: waiterName || 'N/A',
        items: isNewOrder ? items : undefined,
        changes: !isNewOrder ? changes : undefined,
        printType: printType || (isNewOrder ? 'new_order' : 'order_update'),
        timestamp: new Date().toISOString()
      };
      global.io.emit('new-print-data', printDataForSocket);
      console.log('✓ Print data broadcasted via Socket.IO');
    }

    res.status(200).json({ 
      success: true, 
      message: 'Print data saved successfully',
      printDataId: printData._id
    });

  } catch (error) {
    console.error('Error saving print data:', error);
    res.status(500).json({ 
      success: false, 
      message: 'Error saving print data',
      error: error.message 
    });
  }
};

