const JWT = require('jsonwebtoken');
const cfg = require('./config');
const ServerUser = require('./db/user/User');


async function checkValidCredentials ({user, password, jwt}) {
	if (jwt) {
		try {
			const decoded = JWT.verify(jwt,  cfg.jwt.secret, {maxAge: "1d"});
			delete decoded.iat;
			delete decoded.exp;
			return decoded;
		} catch (err) {
			console.warn("Failed to verify credentials for", jwt);
			console.warn(err);

			if (err instanceof JWT.TokenExpiredError) {
				const payload = JWT.decode(jwt);
				if (payload?.id) {
					const user = await ServerUser.fromSQL(null, payload.id);
					if (user?.active) {
						// We should still be good, though the user might have
						// change organisations and such. This will hopefully
						// cause the JWT to be reissued.
						return user.toJSON();
					}
				}
			}

			return; // Invalid JWT
		}
	} else if (user && password) {
		return (await ServerUser.authenticateSQL(user, password))?.toJSON();
	}
}

function issue (payload, req, res) {

	const token = JWT.sign(payload, cfg.jwt.secret, cfg.jwt.options);

	if (req) {
		req.user = payload;
	}

	if (res) {
		if (token) {
			res.set("X-JWT", token);
			const expiry = payload.exp ? (new Date(payload.exp*1000)).toUTCString() : null;
		}
	}

	return token;
}

module.exports = {
	checkValidCredentials,
	issue,
	decode: JWT.decode
};
