const jwt = require('jsonwebtoken');
const { UnauthorizedError } = require('./errors');

/**
 * Generate JWT token for a user
 * @param {Object} user - User object
 * @returns {string} JWT token
 */
const generateToken = (user) => {
  const payload = {
    user: {
      id: user.id,
      email: user.email,
      name: user.name,
      role: user.role_name || 'customer', // Default to customer role
      permissions: user.permissions || []
    }
  };

  return jwt.sign(payload, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN || '24h'
  });
};

/**
 * Verify and decode JWT token
 * @param {string} token - JWT token
 * @returns {Object} Decoded token payload
 */
const verifyToken = (token) => {
  try {
    if (!token) {
      throw new UnauthorizedError('No token provided');
    }

    // Remove 'Bearer ' if present
    if (token.startsWith('Bearer ')) {
      token = token.split(' ')[1];
    }

    return jwt.verify(token, process.env.JWT_SECRET);
  } catch (error) {
    if (error.name === 'TokenExpiredError') {
      throw new UnauthorizedError('Token expired');
    }
    if (error.name === 'JsonWebTokenError') {
      throw new UnauthorizedError('Invalid token');
    }
    throw error;
  }
};

/**
 * Get user from JWT token
 * @param {string} token - JWT token
 * @returns {Object} User object from token
 */
const getUserFromToken = (token) => {
  const decoded = verifyToken(token);
  return decoded.user;
};

module.exports = {
  generateToken,
  verifyToken,
  getUserFromToken
};
