const jwt = require('jsonwebtoken');
const { updateOrCreateToken } = require('../../helpers');
const { errorHandler } = require('../../util');

exports.refreshAccessToken = (req, res, next) => {
	const { refreshToken } = req.body;

	jwt.verify(refreshToken, process.env.SECRETKEY, (err, decoded) => {
		if (err) {
			return errorHandler('Invalid or expired refresh token', 401);
		}

		const { userId, isHost, hasPendingApplication, deviceId } = decoded;

		updateOrCreateToken(userId, req, { isHost, hasPendingApplication, deviceId })
			.then(({ token: newAccessToken }) => {
				res.json({
					success: true,
					message: 'New access token generated successfully.',
					token: newAccessToken,
					refreshToken,
				});
			})
			.catch((err) => {
				next(err);
			});
	});
};
