// middleware/authMiddleware.js
const jwt = require('jsonwebtoken');
const User = require('../models/Customer'); // Assuming you have a User model
const Labour = require('../models/Labour'); // Make sure this is imported

// This is for customer protection
exports.protect = async (req, res, next) => {
  let token;

  if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
    try {
      token = req.headers.authorization.split(' ')[1];
      //console.log('Customer Auth - Received token:', token);

      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      //console.log('Customer Auth - Decoded JWT payload:', decoded);

      req.user = await User.findById(decoded.id).select('-password');
      //console.log('Customer Auth - User found in DB:', req.user ? req.user.name : 'None');

      if (!req.user) {
        //console.log('Customer Auth - Authentication failed: User not found for ID', decoded.id);
        return res.status(401).json({ message: 'Not authorized, user not found' });
      }

      next();
    } catch (error) {
      console.error('Customer Auth Middleware Error:', error.message);
      if (error.name === 'TokenExpiredError') {
        return res.status(401).json({ message: 'Not authorized, token expired' });
      } else if (error.name === 'JsonWebTokenError') {
        return res.status(401).json({ message: 'Not authorized, invalid token' });
      }
      res.status(401).json({ message: 'Not authorized, token failed' });
    }
  } else {
    //console.log('Customer Auth - Authentication failed: No token provided in headers.');
    res.status(401).json({ message: 'Not authorized, no token' });
  }
};

// This is for labourer protection
exports.protectLabour = async (req, res, next) => {
  let token;
  if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
    try {
      token = req.headers.authorization.split(' ')[1];
      //console.log('Labour Auth - Received token:', token); // Log the received token

      // Use process.env.JWT_SECRET here too!
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      //console.log('Labour Auth - Decoded JWT payload:', decoded); // Log the decoded payload

      if (decoded.userType && decoded.userType !== 'labourer') {
        //console.log('Labour Auth - Forbidden: Invalid user type in token.', decoded.userType);
        return res.status(403).json({ message: 'Forbidden: Invalid user type for this route.' });
      }

      req.labour = await Labour.findById(decoded.id).select('-password');
      //console.log('Labour Auth - Labour found in DB:', req.labour ? req.labour.name : 'None');

      if (!req.labour) {
        //console.log('Labour Auth - Authentication failed: Labourer not found for ID', decoded.id);
        return res.status(401).json({ message: 'Not authorized, labourer not found' });
      }

      next();
    } catch (error) {
      // Enhanced logging for specific JWT errors
      console.error('Labour Auth Middleware Error during token verification:', error.message);
      if (error.name === 'TokenExpiredError') {
        return res.status(401).json({ message: 'Not authorized, token expired' });
      } else if (error.name === 'JsonWebTokenError') {
        return res.status(401).json({ message: 'Not authorized, invalid token' });
      }
      res.status(401).json({ message: 'Not authorized, labourer token failed' });
    }
  } else {
    //console.log('Labour Auth - Authentication failed: No token provided in headers.');
    res.status(401).json({ message: 'Not authorized, no token provided' });
  }
};
