import jwt from 'jsonwebtoken';

const secret = process.env.JWT_SECRET;

if (!secret) {
  throw new Error('Environment variable JWT_SECRET needs to be defined');
}

export function authenticateJwtCookie(excludedRoutes) {
  return function (req, res, next) {
    const token = req.cookies?.jwt;
    const skipCheck = excludedRoutes.includes(req.path);

    if (!token && !skipCheck) {
      console.error('No cookie provided');
      return res.status(401).end();
    }

    jwt.verify(token, secret, (err, decodedData) => {
      if (err && !skipCheck) {
        console.error(err);
        return res.status(401).end();
      } else {
        req.jwtData = decodedData;
        return next();
      }
    });
  }
}

export function setJwtCookie(data, res) {
  res.cookie('jwt', jwt.sign(data, secret), {
    httpOnly: true, // security: don't expose the cookie to the JavaScript
    sameSite: 'strict', // security: mitigate CSRF
    secure: false,
  });
}
