import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
const JWT_SECRET = process.env.JWT_SECRET || 'restaurant-menu-secret-key-change-in-production';

export const hashPassword = async (password) => {
  return await bcrypt.hash(password, 12);
};

export const verifyPassword = async (password, hash) => {
  return await bcrypt.compare(password, hash);
};

export const generateToken = (user) => {
  const payload = {
    id: user.id,
    email: user.email,
    name: user.name,
    role: user.role,
    restaurant_id: user.restaurant_id
  };
  return jwt.sign(payload, JWT_SECRET, { expiresIn: '24h' });
};

export const verifyToken = (token) => {
  try {
    return jwt.verify(token, JWT_SECRET);
  } catch (error) {
    return null;
  }
};
export const authMiddleware = async (req, res, next) => {
  const authHeader = req.headers.authorization;
  
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ success: false, message: 'No token provided' });
  }

  const token = authHeader.substring(7);
  const decoded = verifyToken(token);

  if (!decoded) {
    return res.status(401).json({ success: false, message: 'Invalid token' });
  }
  req.user = decoded;
  next();
};
export const adminMiddleware = async (req, res, next) => {
  const user = req.user;
  
  if (!user || user.role !== 'super_admin') {
    return res.status(403).json({ success: false, message: 'Super admin access required' });
  }

  next();
};
export const restaurantAdminMiddleware = async (req, res, next) => {
  const user = req.user;
  
  if (!user || (user.role !== 'super_admin' && user.role !== 'restaurant_admin')) {
    return res.status(403).json({ success: false, message: 'Admin access required' });
  }

  next();
};