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

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

const User = models.User;

passport.use(new LocalStrategy(
    { usernameField: 'username' },
    async function(username, password, done) { 
        try {  
            const utilisateurs = await User.find({});
            console.log("----", utilisateurs)
            const user = await User.findOne({ username: username });
            if (!user) {
                /*
                const newUser = new User({
                    username: username,
                    password: password 
                });
                await newUser.save();
                */
                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;