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

const initializePassport = require('../middleware/passport-config')

initializePassport(
    passport,
    email => User.findOne({ email: email }, function (err, adventure) {}),
    id => User.findById(id, function (err, adventure) {})
  )

  exports.checkAuthenticated=(req, res, next)=>   {
  if (req.isAuthenticated()) {
    return next()
  }

  res.redirect('/users/login')
}

exports.checkNotAuthenticated = (req, res, next) =>  {
  if (req.isAuthenticated()) {
    return res.render('../views/user/user', {error : "you are connected"})
  }
  next()
}

exports.goToRegister = (req, res) =>{
    res.render('../views/user/register');
}

exports.goToUser = (req, res) =>{
  res.render('../views/user/user');
}

exports.register = async (req, res) => {
  console.log(req.body)
  try {
    const hashedPassword = await bcrypt.hash(req.body.password, 10)
    req.body.password= hashedPassword 
    let us = await (new User(req.body)).save()
    res.redirect('/users/login')
  } catch (err){
    console.log(err.message)
    res.redirect('/users/register')
  }
}





exports.goToLogin = (req, res) =>{
  res.render('../views/user/login');
}