import { expressjwt } from 'express-jwt';
import util from 'util';
import getConfig from 'next/config';
import jwt from 'jsonwebtoken';

const { serverRuntimeConfig } = getConfig();

export { jwtMiddleware };

async function jwtMiddleware(req, res) {
     const publicRoutes = [
          '/api/users/register',
          '/api/users/authenticate',
     ];

     const isPublicRoute = publicRoutes.some(route => req.url.startsWith(route));

     if (isPublicRoute) {
          return;
     } 


     const middleware = expressjwt({ secret: serverRuntimeConfig.secret, algorithms: ['HS256'] });

     const headerToken = req.headers.authorization;
     if (!headerToken) return res.status(401).json({ error: "Invalid token!" });

     const token = headerToken.replace(/^Bearer\s+/i, '');

     try {
          const decodedToken = await util.promisify(jwt.verify)(token, serverRuntimeConfig.secret);
          req.userID = decodedToken.sub;
          req.userName = decodedToken.name; 
      
          await util.promisify(middleware)(req, res);
       
     } catch (err) {
          return res.status(401).json({ error: 'Unauthorized - Invalid token' });
     }
}