const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');
const { errorHandler } = require('../../util');
const { ConventionUsers } = require('../../models');

dotenv.config();

module.exports = async (req, res, next) => {
	try {
		const authHeader = req.get('Authorization');
		if (!authHeader) {
			return errorHandler('Not authenticated', 401);
		}

		const token = authHeader.split(' ')[1];
		const decodedToken = jwt.verify(token, process.env.CONVENTION_SECRET_KEY);

		if (!decodedToken) {
			return errorHandler('Not Authenticated', 401);
		}

		const convention = await ConventionUsers.findByPk(decodedToken.conventionId);

		if (!convention) {
			return errorHandler('Convention User token not valid.', 401);
		}

		req.conventionId = decodedToken.conventionId;
		req.userType = decodedToken.userType;
		req.user = convention;

		next();
	} catch (err) {
		console.error(err);
		next(err);
	}
};
