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


const secretKey = process.env.JWT_SECRET; // Load secret from .env file

dotenv.config();


// Controller: Login a user
exports.login = async (req, res) => {
  const { username, password } = req.body;

 //console.log("send data is",req.body)
 const user = await User.find();
 //console.log(user)
  try {
    // Step 1: Find the user in the database
    const user = await User.findOne({ username }).populate(['branchId', 'companyId']);

    if (!user) {
      return res.status(400).json({ message: 'Invalid credentials' });
    }

    // Step 2: Validate the password
    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) {
      return res.status(400).json({ message: 'Invalid credentials' });
    }

    // Step 3: Check that JWT_SECRET is defined in environment variables
    if (!secretKey) {
      throw new Error('JWT_SECRET is not defined in environment variables');
    }

    // Step 4: Create a JWT token
 

    const populatedUser = await User.findById(user._id)
    .populate({
      path: 'roleId',
      populate: { path: 'permission' },
    })
    .populate('allowedBranchId'); // Populate allowedBranchId
  
  // Generate JWT Token
  const token = jwt.sign(
    {
      userId: user._id,
      companyName: user.companyId.name,
      branchName: user.branchId.name,
      companyId: user.companyId._id,
      branchId: user.branchId._id,
      branchType: user.branchId.type,
      defaultAction: user.branchId.defaultAction,
      kitchenId:user.kitchenId, 
            allowedBranchId: populatedUser.allowedBranchId.map(branch => ({
        id: branch._id,
        name: branch.name,
      })), // Include allowedBranchId names and IDs
      permission: populatedUser.roleId.permission.map((p) => p.name),
    },
    secretKey,
    { expiresIn: '1h' }
  );
  

    // Step 5: Save session information (if using session-based authentication)
    req.session.user = {
       id: user._id,
       username: user.username,
       companyName: user.companyId.name,
        branchName: user.branchId.name,
        companyId: user.companyId._id,
        branchId: user.branchId._id,
        branchType:user.branchId.type,
        defaultAction:user.branchId.defaultAction,
       permission: populatedUser.roleId.permission.map((p) => p.name),
    };



    req.user = {
      id: user._id,
      username: user.username,
      companyName: user.companyId.name,
       branchName: user.branchId.name,
       companyId: user.companyId._id,
       branchId: user.branchId._id,
       branchType:user.branchId.type,
       defaultAction:user.branchId.defaultAction,
      permission: populatedUser.roleId.permission.map((p) => p.name),
   };

   if(req.body.fcmToken!=null&&req.body.fcmToken!='') {

    console.log("device token is " + req.body.fcmToken);
      
    user.fcmToken = req.body.fcmToken;
    await user.save();
    console.log("FCM token updated for user " + user._id);
  }
     
    // Step 6: Send token back to the client
    res.json({ token });
  } catch (error) {
    console.error('Error during login:', error);
    res.status(500).json({ message: 'An error occurred during login' });
  }
};

// Controller: Logout a user
exports.logout = (req, res) => {
  // Destroy the session on logout
  req.session.destroy((err) => {
    if (err) {
      return res.status(500).json({ message: 'Error logging out' });
    }
    res.clearCookie('connect.sid'); // Clear session cookie
    res.render('login'); // Pass currentPage to the view
 
   // res.status(200).json({ message: 'Logout successful' });
  });
};
// Controller: Change Password
exports.changePassword = async (req, res) => {
  const userId  = req.session.user.id; // Assuming user ID is available from authentication middleware

  console.log("user id is",req.session.user.id)
  const { currentPassword, newPassword } = req.body;

  try {
    // Step 1: Find the user by ID
    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({ message: 'User not found' });
    }

    // Step 2: Validate the current password
    const isMatch = await bcrypt.compare(currentPassword, user.password);
    if (!isMatch) {
      return res.status(400).json({ message: 'Current password is incorrect' });
    }

    // Step 3: Hash the new password
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(newPassword, salt);

    // Step 4: Update the user's password
    user.password = hashedPassword;
    await user.save();

    // Step 5: Respond to the client
    res.status(200).json({ message: 'Password changed successfully' });
  } catch (error) {
    console.error('Error changing password:', error);
    res.status(500).json({ message: 'An error occurred while changing password' });
  }
};
