const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

const User = require('./schemas/models');

passport.use(new LocalStrategy(
    { usernameField: 'username' },
    async function(username, password, done) { 
        try {  
            // const utilisateurs = await User.find({});
            const user = await User.findOne({ username: username });
            if (!user) {
                return done(null, false, { message: 'Nom d\'utilisateur incorrect.' });
            }
            if (!user.validPassword(password)) {
                return done(null, false, { message: 'Mot de passe incorrect.' });
            }
            return done(null, user);
        } catch (error) {
            return done(error);
        }
    }
));

passport.serializeUser(function(user, done) {
    done(null, user.username);
});

passport.deserializeUser( async function(username, done) {
    try {
        const user = await User.findOne({ username: username });
        if (!user) {
            return done(null, false, { message: 'Utilisateur non trouvé.' });
        }
        return done(null, user);
    } catch (error) {
        return done(error);
    }
});

module.exports = passport;