const jwt = require('jsonwebtoken');
const { JWT_SECRET } = require('../../config/keycloak.js');
const prisma = require('../prisma/PrismaClient.js');

const errorMessage = async (res, message, status_code) => {
    return res.status(status_code).json({ status: false, message })
}

const verifyJWT = async (req, res, next) => {
    const authHeader = req.headers.authorization;

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
        return errorMessage(res, 'Token not provided.', 401);
    }

    const token = authHeader.split(' ')[1];

    try {
        const decoded = jwt.verify(token, JWT_SECRET);

        const revoked = await prisma.revokedToken.findFirst({
            where: { token: token },
        });

        if (revoked) {
            return errorMessage(res, 'Token has been revoked.', 401);
        }

        req.user = decoded;
        next();
    } catch (err) {
        if (err.name === 'TokenExpiredError') {
            return errorMessage(res, 'Token has expired.', 401);
        } else if (err.name === 'JsonWebTokenError') {
            return errorMessage(res, 'Invalid token.', 403);
        } else if (err.name === 'NotBeforeError') {
            return errorMessage(res, 'Token not active yet.', 401);
        } else {
            return errorMessage(res, 'Internal server error while verifying token.', 500);
        }
    }
};

module.exports = verifyJWT;