import jwt from 'jsonwebtoken';
import { redisClient } from './redisClient'


export class JwtAuth {


    generateAccessToken(username) {
        return jwt.sign(username, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '30m' });
    }

    generateRefreshToken(user) {
        let refreshToken = jwt.sign(user, process.env.REFRESH_TOKEN_SECRET);


        redisClient.set(refreshToken, JSON.stringify(user), (err, reply) => {
            if (err || reply !== 'OK') {
                refreshToken = null;
            }
        });

        return refreshToken;
    }

    verifyRefreshToken(refreshToken, callback) {

        redisClient.get(refreshToken, (err, value) => {
            if (value) {
                jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET, callback);
            } else {
                callback("Invalid Refresh Token");
            }
        });
    }

    verifyAccessToken(accessToken, callback) {
        jwt.verify(accessToken, process.env.ACCESS_TOKEN_SECRET, callback);
    }

    deleteRefreshToken(refreshToken, callback) {

        redisClient.del(refreshToken, callback);

    }
}


export const jwtAuth = new JwtAuth();