import jwt from 'jsonwebtoken';
import Logs from '../libs/logs.js';

const authMiddleware = (req, res, next) => {
  const token = req.headers['authorization']?.replace('Bearer ', '');

  if (!token) {
    return res.unauthorized('未提供 token');
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.userId = decoded.userId;
    next();
  }
  catch (err) {
    Logs.errDev('token验证错误:', err.message);
    res.unauthorized('无效或已过期的 token');
  }
};

export default authMiddleware;
