text: const crypto = require('crypto');
  const bcrypt = require('bcryptjs');
  const User = require('../models/user');
  const nodemailer = require('nodemailer');
  const sendgridTransport = require('nodemailer-sendgrid-transport');
  const { validationResult } = require('express-validator')
  
  const SENDGRID_API_KEY = process.env.SENDGRID_API_KEY;
  
  const transporter = nodemailer.createTransport(sendgridTransport({
    auth: {
      api_key: SENDGRID_API_KEY
    }
  }));
  
  exports.getLogin = (req, res, next) => {
    let message = req.flash('error');
    if (message.length > 0) {
      message = message[0]
    } else {
      message = null;
    }
    res.render('auth/login', {
      path: '/login',
      pageTitle: 'Login',
      errorMessage: message,
      oldInput: {
        email: '',
        password: ''
      }
    });
  };
  
  exports.getSignup = (req, res, next) => {
    let message = req.flash('error');
    if (message.length > 0) {
      message = message[0]
    } else {
      message = null;
    }
    res.render('auth/signup', {
      path: '/signup',
      pageTitle: 'Signup',
      errorMessage: message,
      oldInput: {
        email: '',
        password: '',
        confirmPassword: ''
      }
    });
  };
  
  exports.postLogin = (req, res, next) => {
    // res.setHeader('Set-Cookie', 'isLoggedIn=true; HttpOnly')
    const email = req.body.email;
    const password = req.body.password;
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(422).render('auth/login', {
        path: '/login',
        pageTitle: 'Login',
        errorMessage: errors.array()[0].msg,
        oldInput: {
          email: email,
          password: password
        }
      })
    }
  
    User.findOne({ email: email })
      .then(user => {
        if (!user) {
          return res.status(422).render('auth/login', {
            path: '/login',
            pageTitle: 'Login',
            errorMessage: 'Invalid email or password!!!',
            oldInput: {
              email: email,
              password: password
            }
          })
        }
        bcrypt.compare(password, user.password)
          .then(doMatch => {
            if (doMatch) {
              req.session.isLoggedIn = true;
              req.session.user = user;
              return req.session.save((err) => {
                console.log(err);
                res.redirect('/');
              });
            }
            return res.status(422).render('auth/login', {
              path: '/login',
              pageTitle: 'Login',
              errorMessage: 'Invalid email or password!!!',
              oldInput: {
                email: email,
                password: password
              }
            })
          }).catch(err => res.redirect("/login"));
      }).catch(err => console.log(err));
  };
  
  exports.postSignup = (req, res, next) => {
    const email = req.body.email;
    const password = req.body.password;
    const errors = validationResult(req);
  
    if (!errors.isEmpty()) {
      return res.status(422).render('auth/signup', {
        path: '/signup',
        pageTitle: 'Signup',
        errorMessage: errors.array()[0].msg,
        oldInput: {
          email: email,
          password: password,
          confirmPassword: req.body.confirmPassword
        }
      });
    }
  
    bcrypt
      .hash(password, 12)
      .then(hashedPassword => {
        const user = new User({
          email: email,
          password: hashedPassword,
          cart: { items: [] },
          name: "NA"
        });
        return user.save();
      })
      .then(result => {
        res.redirect('/login');
        return transporter.sendMail({
          to: email,
          from: 'shop@node-complete.com',
          subject: 'Signup Succeeded',
          html: '<h1> You Successfully signed up!!!</h1>'
        })
      }).catch(err => console.log(err));
  };
  
  exports.postLogout = (req, res, next) => {
    req.session.destroy((err) => {
      console.log(err)
      res.redirect('/');
    })
  };
  
  exports.getResetPassword = (req, res, next) => {
    let message = req.flash('error');
    if (message.length > 0) {
      message = message[0]
    } else {
      message = null;
    }
    res.render('auth/reset', {
      path: '/reset',
      pageTitle: 'Reset Password',
      errorMessage: message,
    });
  };
  
  
  exports.postResetPassword = (req, res, next) => {
    crypto.randomBytes(32, (err, buffer) => {
      if (err) {
        return res.redirect('/reset');
      }
      const token = buffer.toString('hex');
      User.findOne({ email: req.body.email })
        .then(user => {
          if (!user) {
            req.flash('error', 'No account with that email found!!!');
            return res.redirect('/reset');
          }
          user.resetToken = token;
          user.resetTokenExpiration = Date.now() + 3600000;
          return user.save();
        })
        .then(result => {
          res.redirect('/');
          transporter.sendMail({
            to: req.body.email,
            from: 'shop@node-complete.com',
            subject: 'Password Reset',
            html: `
            <p>You requested a password reset</p>
            <p>Click this <a href="http://localhost:3000/reset/${token}"> link </a> to set a new password.</p>
            `
          })
        })
        .catch(err => console.log(err))
    })
  }
  
  exports.getNewPassword = (req, res, next) => {
    const token = req.params.token;
    User.findOne({ resetToken: token, resetTokenExpiration: { $gt: Date.now() } })
      .then(user => {
        let message = req.flash('error');
        if (message.length > 0) {
          message = message[0]
        } else {
          message = null;
        }
        res.render('auth/newpassword', {
          path: '/newpassword',
          pageTitle: 'New Password',
          errorMessage: message,
          userId: user._id.toString(),
          paasswordToken: token
        });
      })
      .catch(err => console.log(err));
  }
  
  exports.postNewPassword = (req, res, next) => {
    const newpassword = req.body.password;
    const userId = req.body.userId;
    const paasswordToken = req.body.paasswordToken;
    let resetUser;
  
    User.findOne({
      resetToken: paasswordToken,
      resetTokenExpiration: { $gt: Date.now() },
      _id: userId
    })
      .then(user => {
        resetUser = user;
        return bcrypt.hash(newpassword, 12)
      })
      .then(hashedPassword => {
        resetUser.password = hashedPassword;
        resetUser.resetToken = undefined;
        resetUser.resetTokenExpiration = undefined;
        return resetUser.save();
      })
      .then(result => {
        res.redirect('/login')
      })
      .catch(err => console.log(err))
  }