const jwt = require('jsonwebtoken');
const env = require('../config/env');

/**
 * JWT Utility Functions
 * Handles token generation and verification
 */

/**
 * Generate JWT token for a user
 * @param {Object} payload - User data to encode in token
 * @param {string} payload.userId - User ID
 * @param {string} payload.type - Token type ('user' or 'admin')
 * @param {Object} options - Token options
 * @returns {string} JWT token
 */
const generateToken = (payload, options = {}) => {
  const defaultOptions = {
    expiresIn: env.jwt.expiresIn || '7d',
  };

  return jwt.sign(payload, env.jwt.secret, { ...defaultOptions, ...options });
};

/**
 * Verify and decode JWT token
 * @param {string} token - JWT token to verify
 * @returns {Object} Decoded token payload
 * @throws {Error} If token is invalid or expired
 */
const verifyToken = (token) => {
  try {
    return jwt.verify(token, env.jwt.secret);
  } catch (error) {
    if (error.name === 'TokenExpiredError') {
      throw new Error('Token has expired');
    }
    if (error.name === 'JsonWebTokenError') {
      throw new Error('Invalid token');
    }
    throw error;
  }
};

/**
 * Generate refresh token
 * @param {Object} payload - User data to encode
 * @returns {string} Refresh token
 */
const generateRefreshToken = (payload) => {
  return generateToken(payload, { expiresIn: '30d' });
};

/**
 * Decode token without verification (for debugging)
 * @param {string} token - JWT token
 * @returns {Object|null} Decoded payload or null
 */
const decodeToken = (token) => {
  return jwt.decode(token);
};

module.exports = {
  generateToken,
  verifyToken,
  generateRefreshToken,
  decodeToken,
};
