const jwt = require('jsonwebtoken');
const { hashPassword, verifyPassword, verifyToken } = require('../utils/auth');

const JWT_SECRET = process.env.JWT_SECRET;

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

const authenticate = (req, res, next) => {
  const token = req.headers.authorization?.replace('Bearer ', '');
  
  if (!token) {
    return res.status(401).json({ success: false, message: '未提供认证令牌' });
  }
  
  const decoded = verifyToken(token);
  
  if (!decoded) {
    return res.status(401).json({ success: false, message: '无效的认证令牌' });
  }
  
  req.user = decoded;
  next();
};

const optionalAuth = (req, res, next) => {
  const token = req.headers.authorization?.replace('Bearer ', '');
  
  if (!token) {
    req.user = null;
    next();
    return;
  }
  
  const decoded = verifyToken(token);
  
  if (!decoded) {
    req.user = null;
    next();
    return;
  }
  
  req.user = decoded;
  next();
};

const requireRole = (roles) => {
  return (req, res, next) => {
    if (!req.user) {
      return res.status(401).json({ success: false, message: '未授权' });
    }
    
    if (!roles.includes(req.user.role)) {
      return res.status(403).json({ success: false, message: '权限不足' });
    }
    
    next();
  };
};

const requireAdmin = (req, res, next) => {
  return requireRole(['admin'])(req, res, next);
};

module.exports = {
  authenticate,
  optionalAuth,
  requireRole,
  requireAdmin,
  generateToken,
  verifyToken,
  hashPassword,
  verifyPassword
};
