const jwt = require('jsonwebtoken');
const { RefreshTokens } = require('../models');
const { generateDeviceId } = require('./device-id-helper');
const { getBrowserInfo } = require('./get-browser-info');

const generateToken = (data, expiresIn = '2hrs') => {
	return jwt.sign(data, process.env.SECRETKEY, {
		expiresIn,
	});
};

const updateOrCreateToken = async (userId, req, { isHost, hasPendingApplication }) => {
	try {
		const deviceId = generateDeviceId(req);
		const { browser, version, platform, device } = getBrowserInfo(req);

		const token = generateToken({ userId, isHost, hasPendingApplication }, '2hrs');
		const refreshToken = generateToken({ userId, isHost, hasPendingApplication, deviceId }, '30d');

		const existingToken = await RefreshTokens.findOne({
			where: { user_id: userId, device_id: deviceId },
		});

		if (existingToken) {
			await existingToken.update({
				token,
				expiration_date: new Date(Date.now() + 2 * 60 * 60 * 1000),
				browser: `${browser} ${version}`,
				os: platform,
				device,
			});
		} else {
			await RefreshTokens.create({
				user_id: userId,
				token,
				refresh_token: refreshToken,
				expiration_date: new Date(Date.now() + 2 * 60 * 60 * 1000),
				refresh_token_expiration_date: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
				device_id: deviceId,
				browser: `${browser} ${version}`,
				os: platform,
				device,
			});
		}

		return { token, refreshToken };
	} catch (err) {
		throw err;
	}
};

module.exports = { generateToken, updateOrCreateToken };
