const jwt = require('jwt-simple');
const User = require('../models/user');
const config = require('../config');

// Create the token to be sent to the client
// PS: JWT is a convention. So, they have some properties predefined.
// Sub is for subject
// iat is for issued at time
// More information in https://jwt.io
function tokenForUser(user) {
  const timestamp = new Date().getTime();
  // Its better to use the id property from the user because the email can sometimes change
  // The user ID is a property that is included on the user model by MongoDB by default
  return jwt.encode({ sub: user.id, iat: timestamp }, config.secret);
}

// Handle the signin request
exports.signin = function(req, res, next) {
  // User has already had their email and password auth'd
  // We just need to give them a token
  res.send({ token: tokenForUser(req.user) });
}

// Handle the signup request
exports.signup = function(req, res, next) {
  const email = req.body.email;
  const password = req.body.password;

  if (!email || !password) {
    return res.status(422).send({ error: 'You must provide email and password'});
  }

  // See if a user with the given email exists
  User.findOne({ email: email }, function(err, existingUser) {
    if (err) { return next(err); }

    // If a user with email does exist, return an error
    if (existingUser) {
      return res.status(422).send({ error: 'Email is in use' });
    }

    // If a user with email does NOT exist, create and save user record
    const user = new User({
      email: email,
      password: password
    });

    user.save(function(err) {
      if (err) { return next(err); }

      // Repond to request indicating the user was created
      res.json({ token: tokenForUser(user) });
    });
  });
}
