const passport = require('passport');
const { ConventionUsers, Events } = require('../../../models');
const CustomStrategy = require('passport-custom').Strategy;
const LocalStrategy = require('passport-local').Strategy;

// passport.use(
// 	'signup-member',
// 	new CustomStrategy(async (req, done) => {
// 		try {
// 			const {
// 				organization_name,
// 				is_jci_senator,
// 				local_org_name,
// 				first_name,
// 				last_name,
// 				email_address,
// 				password,
// 				is_tnc_agreed,
// 			} = formatCase(req.body, 'snake');

// 			const existingUser = await Members.findOne({
// 				where: {
// 					email_address: email_address,
// 				},
// 			});

// 			if (existingUser) {
// 				return done(null, false, { message: 'Email address is already in use.' });
// 			}

// 			const member = await Members.create({
// 				organization_name,
// 				is_jci_senator,
// 				local_org_name,
// 				first_name,
// 				last_name,
// 				email_address,
// 				password,
// 				is_tnc_agreed,
// 			});

// 			return done(null, member);
// 		} catch (error) {
// 			done(error);
// 		}
// 	}),
// );

passport.use(
	'login-convention',
	new LocalStrategy(
		{ usernameField: 'emailAddress', passReqToCallback: true },
		async (req, emailAddress, password, done) => {
			try {
				const convention = await ConventionUsers.findOne({
					where: {
						email_address: emailAddress,
					},
					include: [
						{
							model: Events,
							as: 'event',
						},
					],
				});

				if (!convention || !(await convention.validatePassword(password))) {
					return done(null, false, { message: 'Invalid email/phone or password' });
				}

				return done(null, convention);
			} catch (error) {
				return done(error);
			}
		},
	),
);

passport.serializeUser((convention, done) => {
	done(null, convention.id);
});

passport.deserializeUser(async (id, done) => {
	try {
		const convention = await ConventionUsers.findByPk(id);
		done(null, convention);
	} catch (error) {
		done(error);
	}
});

module.exports = passport;
