import jwt from 'jsonwebtoken';
import config from "config";
import Token from '../models/Token.js';

class TokenService {
    generateTokens(payload) {
        const accessToken = jwt.sign(payload, config.get("JWTAccessSecret"), {expiresIn: "30m"});
        const refreshToken = jwt.sign(payload, config.get("JWTRefreshSecret"), {expiresIn: "30d"});
        
        return { accessToken, refreshToken }
    }

    validateAccessToken(token) {
        try {
            const user = jwt.verify(token, config.get("JWTAccessSecret"))
            return user;
        } catch (e) {
            return null;
        }
    }

    validateRefreshToken(token) {
        try {
            const user = jwt.verify(token, config.get("JWTRefreshSecret"))
            return user;
        } catch (e) {
            return null;
        }
    }

    async saveToken(userId, refreshToken) {
        const candidate = await Token.findOne({ user: userId });
        if (candidate) {
            candidate.refreshToken = refreshToken;
            return candidate.save();
        }
        const token = await Token.create({ user: userId, refreshToken });
        return token;
    }

    async removeToken(refreshToken) {
        const deletedToken = await Token.deleteOne({ refreshToken });
        return deletedToken;
    }
    
    async findToken(refreshToken) {
        const token = await Token.findOne({ refreshToken });
        return token;
    }
}

export default new TokenService();