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

const checkOrCreatedeviceId = async (req, res, next) => {
  try {
  //  console.log("Cookies received:", req.cookies);

    let deviceId_1 = req.cookies.deviceId_1;

    const countDevices = await Device.countDocuments();
    console.log(`Total devices: ${countDevices}`);
    console.log('incoming device is', deviceId_1);
    // Step 1: Check if the deviceId_1 exists in the cookies
    if (deviceId_1) {

      const existingDevice = await Device.findOne({deviceId: deviceId_1 });

      if (existingDevice) {
       
        if (existingDevice.status === 'approved') {
         return next(); // Allow access for approved devices
        } else {
          return next(); // Allow access for  devices temporarily
          console.log("Device is not approved");
                return res.redirect('http://incor-rect-site.com');
           }
      }
      else {
        console.log(" this device is already have Id but not in database");
        if(countDevices<1) // to allow automatically aproval for first 2 new devices
     
        {        
          const newDevice = new Device({
            deviceId:deviceId_1,
            deviceName: 'Device'+countDevices,
            status: 'approved',
          });
      
          await newDevice.save();
          console.log('New deviceId_1 saved in database with approved status:', deviceId_1);
          return next(); // Allow access for approved devices
      }
      else {
       
        // Step 3: Save the new device in the database with a "pending" status
        const newDevice = new Device({
          deviceId:deviceId_1,
           deviceName: 'Device'+countDevices,
          status: 'pending',
        });
        console.log('New deviceId_1 saved in database with pending approval:', deviceId_1);
       
        await newDevice.save();
        return next();// temporarily allow access for pending devices
        return res.redirect('http://incor-rect-site.com');
      }


       
       // return res.json({ notFound: true }).end(); // Notify device not found
      }
    }

    // Step 2: If no deviceId_1 exists, generate a new UUID
    if (!deviceId_1) {
      deviceId_1 = uuid.v4(); // Generate a new unique identifier

      // Set the deviceId_1 as an HTTP-only cookie
      res.cookie('deviceId_1', deviceId_1, {
        httpOnly: true,
        secure: true,
        sameSite: 'Lax', // Using 'Lax' as default for SameSite
        maxAge: 1000 * 60 * 60 * 24 * 365 * 5, // 5 years expiration
      });

   //   res.json({ deviceId_1 }); // Send deviceId_1 in the response
      console.log('New deviceId_1 generated and set in cookie:', deviceId_1);

   
     
    


   

    

    if(countDevices<1) // to allow automatically aproval for first 3 new devices
     
        { const newDevice = new Device({
          deviceId:deviceId_1,
            deviceName: 'Device'+countDevices,
            status: 'approved',
          });
      
          await newDevice.save();
          console.log('New deviceId_1 saved in database with approved status:', deviceId_1);
  
      }
else {
    // Step 3: Save the new device in the database with a "pending" status
    const newDevice = new Device({
      deviceId:deviceId_1,
       deviceName: 'Device'+countDevices,
      status: 'pending',
    });
    console.log('New deviceId_1 saved in database with pending approval:', deviceId_1);
   
    await newDevice.save();

  }

   // Redirect if necessary
   return next();// temporarily allow access for pending devices
     return res.redirect('http://incor-rect-site.com');
  

}
  } catch (error) {
    console.error('Error in checkOrCreatedeviceId_1:', error);
   res.status(500).json({ error: 'Internal server error' });
  }
};

module.exports = checkOrCreatedeviceId;
