// authMiddleware.js

const jwt = require('jsonwebtoken');
const model = require('../Model');  // Adjust path to your models
const crypto = require('crypto');

const decryptionKey = Buffer.from(process.env.ENCRYPTION_KEY, 'hex');  // Replace with securely stored key
const ivLength = 16;

// Function to decrypt the token
function decryptToken(encryptedData) {
    const parts = encryptedData.split(':');
    const iv = Buffer.from(parts[0], 'hex');
    const encrypted = parts[1];
    
    const decipher = crypto.createDecipheriv('aes-256-cbc', decryptionKey, iv);
    let decrypted = decipher.update(encrypted, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    
    return decrypted;
}

module.exports = {
  authenticate: (strategy, options) => {
    return async (req, res, next) => {
      try {
        if (strategy === 'jwt') {
          const encToken = req.headers.authorization?.split(' ')[1];
          const token = decryptToken(encToken);
          
          if (!token) {
            return res.status(401).json({ message: 'Token not provided.' });
          }
          
          const decoded = jwt.verify(token, process.env.SECRET_KEY);
           if(!decoded){
             return res.status(401).json({ message: 'Invalid token.' });
           }
           const user = await model.User.findById(decoded.id);
           if(!user){
             return res.status(404).json({ message: 'User not found.' });
           }
        // console.log("user: " + user.T_Version);
        // console.log("Decoded Object:", JSON.stringify(decoded, null, 2));
        // console.log("Decoded Object:",decoded.version   );

        
        
           
           if (user.number - decoded.number > user.sessionAllowed) {
             return res.status(401).json({ message: 'Session limit exceeded.' });
           }
           if(user.T_Version!= decoded.version) {
             return res.status(401).json({ message: 'Version mismatch.' });
           }
        
          req.user = user;
          next();
        } else {
          return res.status(400).json({ message: 'Invalid strategy' });
        }
      } catch (error) {
        console.error("Error during authentication:", error);
        return res.status(401).json({ message: 'Unauthorized access.' });
      }
    };
  },
};
