import jwt from 'jsonwebtoken';

import config from '$lib/config';

const SECRET = config.jwt.secret;
const EXPIRES_IN = config.jwt.expiresIn;

const AUTH = config.auth;

export function createToken(userData) {
	return jwt.sign(userData, SECRET, { expiresIn: EXPIRES_IN });
}

export function decryptToken(token) {
	return jwt.verify(token, SECRET);
}

export function authenticate(user, pass) {
	let userData = null;

	if (AUTH[user]) {
		const { password, ...data } = AUTH[user];
		if (password && password === pass) userData = data;
	}

	if (userData == null) return null;

	return createToken({ id: user, ...userData });
}
