const CafeOrderTransfer = require('../models/CafeOrderTransfer');
const CafeOrder = require('../models/CafeOrder');
const User = require('../models/User');
// Create a new CafeOrderTransfer
exports.createCafeOrderTransfer = async (req, res) => {
  try {
    const { userId,waiterId, orderId, status } = req.query;
//console.log ("send data is",req.query);

    const fromUserId=userId;
    const toUserId=waiterId;
  
    const newTransfer = new CafeOrderTransfer({
      fromUserId,
      toUserId,
      orderId,
      status
    });

    const updateOrder= await CafeOrder.findOne({_id:orderId});
    updateOrder.transferStatus = "pending";
    await updateOrder.save();

    await newTransfer.save();
    res.status(201).json({
        message: "Order transferred successfully.",
       
      });
  } catch (error) {
    console.error('Error creating transfer:', error.message);
    res.status(500).json({ message: 'Error creating transfer', error });
  }
};

// Get all CafeOrderTransfers
exports.getAllCafeOrderTransfers = async (req, res) => {
  try {
    const userId= req.query.userId;
    console.log ("send data is",req.query);
  
    const startDate = new Date(new Date().setUTCHours(0, 0, 0, 0));
    const endDate = new Date(new Date().setUTCHours(23, 59, 59, 999));
    
    // Query conditions
    const matchConditions = {
      status: 'pending',
      $or: [
        { toUserId: userId },
        { fromUserId: userId }
      ],
      createdAt: { $gte: startDate, $lte: endDate } // Today's date range
    };
    
    const transfers = await CafeOrderTransfer.find(matchConditions)
      .populate('fromUserId toUserId orderId');

      
    console.log(transfers);
    res.status(200).json(transfers);
  } catch (error) {
    res.status(500).json({ message: 'Error fetching transfers', error });
  }
};


exports.performCafeOrderTransfer = async (req, res) => {
    try {
      const { action, transferId, orderId, userId } = req.body;
  
      console.log("All parameters are", req.body);
  
   
      const transfer = await CafeOrderTransfer.findOne({ _id: transferId });
    console.log(transfer);
    
      const userFrom= await User.findById(transfer. fromUserId);
      const username=userFrom.username;
      console.log(userFrom);
        // Find the transfer by ID

      if (!transfer) {
        return res.status(404).json({ message: 'Transfer not found.' });
      }
  
      // Find the order by ID
      const order = await CafeOrder.findOne({ _id: orderId });
      if (!order) {
        return res.status(404).json({ message: 'Order not found.' });
      }
  
      // Perform action and save data
      if (action === 'accept') {
        transfer.status = 'accepted';
        order.userId = userId;
        order.transferStatus = 'accepted';
        order.transferFrom=username;
  
       
      } else if (action === 'reject') {
        transfer.status = 'rejected';
        order.transferStatus = 'rejected';
  
      
      } else if (action === 'return') {
        transfer.status = 'returned';
        order.transferStatus = 'returned';
  
      
      } else {
        return res.status(400).json({ message: 'Invalid action provided.' });
      }
      await transfer.save();
      await order.save();
      // Send success response once after action is performed
      return res.status(200).json({ message: `Transfer ${action} successfully.` });
  
    } catch (error) {
      console.error('Error performing cafe order transfer:', error.message);
  
      // Return a 500 response for internal server errors
      return res.status(500).json({ message: 'An error occurred while performing the transfer.', error: error.message });
    }
  };
  


// Get a specific CafeOrderTransfer by ID
exports.getCafeOrderTransferById = async (req, res) => {
  try {
    const transfer = await CafeOrderTransfer.findById(req.params.id).populate('fromUserId toUserId orderId');

    if (!transfer) {
      return res.status(404).json({ message: 'Transfer not found' });
    }

    res.status(200).json(transfer);
  } catch (error) {
    res.status(500).json({ message: 'Error fetching transfer', error });
  }
};

// Update a specific CafeOrderTransfer
exports.updateCafeOrderTransfer = async (req, res) => {
  try {
    const { fromUserId, toUserId, orderId, status } = req.body;

    const updatedTransfer = await CafeOrderTransfer.findByIdAndUpdate(
      req.params.id,
      { fromUserId, toUserId, orderId, status },
      { new: true, runValidators: true }
    );

    if (!updatedTransfer) {
      return res.status(404).json({ message: 'Transfer not found' });
    }

    res.status(200).json(updatedTransfer);
  } catch (error) {
    res.status(500).json({ message: 'Error updating transfer', error });
  }
};

// Delete a specific CafeOrderTransfer
exports.deleteCafeOrderTransfer = async (req, res) => {
  try {
    const deletedTransfer = await CafeOrderTransfer.findByIdAndDelete(req.params.id);

    if (!deletedTransfer) {
      return res.status(404).json({ message: 'Transfer not found' });
    }

    res.status(200).json({ message: 'Transfer deleted successfully' });
  } catch (error) {
    res.status(500).json({ message: 'Error deleting transfer', error });
  }
};
