const { ConventionUsers, Events } = require('../../models');
const { errorHandler } = require('../../util');
const { formatCase } = require('../../util/formatter');
const passport = require('../../util/passport/members/member-passport-config');
const jwt = require('jsonwebtoken');

exports.accountCreate = async (req, res, next) => {
	try {
		const data = formatCase(req.body, 'snake');
		const { first_name, middle_name, last_name, email_address, password } = data;

		const existingUser = await ConventionUsers.findOne({ where: { email_address } });
		if (existingUser) {
			return errorHandler('Email already in use.', 409);
		}

		const newUser = await ConventionUsers.create({
			first_name,
			middle_name,
			last_name,
			email_address,
			password,
		});

		const userResponse = newUser.get({ plain: true });
		delete userResponse.password;

		res.status(201).json({ success: true, data: formatCase(userResponse) });
	} catch (error) {
		next(error);
	}
};

exports.conventionLogin = (req, res, next) => {
	passport.authenticate('login-convention', (err, convention, info) => {
		if (err) {
			return next(err);
		}
		if (!convention) {
			return res.status(400).json({ success: false, message: info.message });
		}

		const token = jwt.sign({ conventionId: convention.id, userType: 'Convention' }, process.env.CONVENTION_SECRET_KEY, {
			expiresIn: '2h',
		});

		res.json({ success: true, token });
	})(req, res, next);
};

exports.getProfile = (req, res, next) => {
	const { conventionId } = req;

	ConventionUsers.findOne({
		where: {
			id: conventionId,
		},
		attributes: {
			exclude: ['password'],
		},
		include: [
			{
				model: Events,
				as: 'event',
			},
		],
	})
		.then((data) => {
			if (!data) {
				return errorHandler('Member not found', 404);
			}

			let convention = data.get({ plain: true });

			return res.status(200).json({ success: true, data: formatCase(convention) });
		})
		.catch((err) => {
			next(err);
		});
};
