const Device = require('../models/Device'); // Adjust path as necessary

// Controller to list all pending devices
exports.getPendingDevices = async (req, res) => {
  try {
    console.log('Listing devices for');
    const pendingDevices = await Device.find({});
    console.log("Pending devices:", pendingDevices);
    res.json(pendingDevices);
  } catch (error) {
    console.error('Error fetching pending devices:', error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
};

// Controller to approve or reject a device
exports.approveOrRejectDevice = async (req, res) => {
  const { deviceId, action } = req.body; // Action can be "approve" or "reject"

  try {
    const device = await Device.findOne({ deviceId });

    if (!device) {
      return res.status(404).json({ error: 'Device not found.' });
    }

    // Update the device's status based on the action
    device.status = action === 'approve' ? 'approved' : 'rejected';
    await device.save();

    res.json({ message: `Device ${action}d successfully.` });
  } catch (error) {
    console.error('Error updating device approval status:', error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
};

// Controller to delete a device
exports.deleteDevice = async (req, res) => {
  const { deviceId } = req.body;

  try {
    const device = await Device.findOneAndDelete({ deviceId });

    if (!device) {
      return res.status(404).json({ error: 'Device not found.' });
    }

    res.json({ message: 'Device deleted successfully.' });
  } catch (error) {
    console.error('Error deleting device:', error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
};
