
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')
const db = require("../models");
const User = db.users;


function initialize(passport, getUserByEmail, getUserById) {
  const authenticateUser = async (email, password, done) => {
    //const user = getUserByEmail(email)
    const user = await User.findOne({ email: email }).exec()
    console.log(user)    
    if (user == null) {
      return done(null, false, { message: 'No user with that email' })
    }
   // console.log("user => ",user)
    try {
      if (await bcrypt.compare(password, user.password)) {
        return done(null, user)
      } else {
        return done(null, false, { message: 'Password incorrect' })
      }
    } catch (e) {
      return done(e)
    }
  }

  passport.use(new LocalStrategy({ usernameField: 'email' }, authenticateUser))
  passport.serializeUser((user, done) => done(null, user.id))
  passport.deserializeUser((id, done) => {
    return done(null, getUserById(id))
  })
}

module.exports = initialize