const jwt = require('jsonwebtoken');
const Sentry = require("@sentry/node"); 
const { sendError } = require('../libs/errorCapture');

exports.authMiddleware = (req, res, next) => {
  const token = req.header('Authorization')
  if (!token) {
    const error = { 
      status : false,
      message: 'No token, authorization denied'
  }
    const sentryError = new Error("No token, authorization denied");
    Sentry.captureException(sentryError);
    res.json(error);
    return
  }

  try {
    const decoded = jwt.verify(token.replace('Bearer ', ''), process.env.JWT_SECRET || 'antkey24');
    req.userId = decoded.userId;
    next();
  } catch (error) {
    sendError("Token is not valid")
    res.json({ 
        status : false,
        message: 'Token is not valid'
    });
    return;
  }
};
