const passport = require('passport');
const { Drivers } = require('../../../models');
const { formatCase } = require('../../formatter');
const CustomStrategy = require('passport-custom').Strategy;
const LocalStrategy = require('passport-local').Strategy;

passport.use(
	'signup-driver',
	new CustomStrategy(async (req, done) => {
		try {
			const {
				first_name,
				middle_name,
				last_name,
				phone_no,
				email_address,
				password,
				driver_name,
				conductor_name,
				shuttle_number,
				plate_number,
			} = formatCase(req.body, 'snake');

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

			let driverImg, vehicleImg;
			if (process.env.USE_EXTERNAL_FILE_SERVER == 'true') {
				driverImg = req.files?.driverImg?.[0];
				vehicleImg = req.files?.vehicleImg?.[0];
			} else {
				driverImg = req.body.driverImg;
				vehicleImg = req.body.vehicleImg;
			}

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

			const driver = await Drivers.create({
				first_name,
				middle_name,
				last_name,
				phone_no,
				email_address,
				password,
				driver_name,
				conductor_name,
				shuttle_number,
				plate_number,
				driver_photo: driverImg,
				vehicle_photo: vehicleImg,
				status: 'offline',
			});

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

passport.use(
	'login-driver',
	new LocalStrategy(
		{ usernameField: 'emailAddress', passReqToCallback: true },
		async (req, emailAddress, password, done) => {
			try {
				const driver = await Drivers.findOne({
					where: {
						email_address: emailAddress,
					},
				});

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

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

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

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

module.exports = passport;
