const jwt = require('jsonwebtoken');
const User = require('../models/User'); // Import the User model
const dotenv = require('dotenv');

dotenv.config();
const secretKey = process.env.JWT_SECRET; // Load secret from .env file

// Middleware: Authenticate User
const authenticateUser = async (req, res, next) => {
  try {
    // Step 1: Extract token from Authorization header
    const token = req.headers.authorization?.split(' ')[1]; // Format: Bearer <token>

    if (!token) {
      return res.status(401).json({ message: 'No token provided, authorization denied' });
    }

    // Step 2: Verify token
    const decoded = jwt.verify(token, secretKey);
    if (!decoded.userId) {
      return res.status(401).json({ message: 'Invalid token, authorization denied' });
    }


    console.log('Token decoded:', decoded);
  console.log('Authenticated user:', req.user);

    // Step 3: Fetch the user from the database
    const user = await User.findById(decoded.userId).populate({
      path: 'roleId',
      populate: { path: 'permission' }, // Populate permissions inside role
    });

    if (!user) {
      return res.status(404).json({ message: 'User not found, authorization denied' });
    }

    // Step 4: Attach user details to req.user
    req.user = {
      id: user._id,
      username: user.username,
      role: {
        name: user.roleId.name,
        permissions: user.roleId.permission.map((p) => p.name), // Extract permission names
      },
    };

    console.log('Authenticated user:', req.user);

    // Proceed to the next middleware
    next();
  } catch (error) {
    console.error('Authentication error:', error);
    res.status(401).json({ message: 'Authentication failed, authorization denied' });
  }
};

module.exports = authenticateUser;
