var express = require('express');
var bcrypt = require('bcryptjs');
var jwt = require('jsonwebtoken');
var User = require('../models/User');

var router = express.Router();

var createToken = function(user) {
  return jwt.sign(
    { id: user._id, username: user.username },
    process.env.JWT_SECRET,
    { expiresIn: '1d' }
  );
};

router.post('/register', function(req, res) {
  var username = req.body.username;
  var password = req.body.password;

  if (!username || !password) {
    return res.status(400).json({ message: 'All fields are required' });
  }

  User.findOne({ username: username })
    .then(function(exists) {
      if (exists) {
        return res.status(400).json({ message: 'Username already exists' });
      }
      return bcrypt.hash(password, 10);
    })
    .then(function(hashedPassword) {
      return User.create({ username: username, password: hashedPassword });
    })
    .then(function(user) {
      var token = createToken(user);
      res.status(201).json({
        token: token,
        user: { id: user._id, username: user.username }
      });
    })
    .catch(function(error) {
      res.status(400).json({ message: error.message });
    });
});

router.post('/login', function(req, res) {
  var username = req.body.username;
  var password = req.body.password;

  if (!username || !password) {
    return res.status(400).json({ message: 'All fields are required' });
  }

  User.findOne({ username: username })
    .then(function(user) {
      if (!user) {
        throw new Error('Invalid username or password');
      }
      return bcrypt.compare(password, user.password).then(function(valid) {
        if (!valid) {
          throw new Error('Invalid username or password');
        }
        var token = createToken(user);
        res.json({
          token: token,
          user: { id: user._id, username: user.username }
        });
      });
    })
    .catch(function(error) {
      res.status(500).json({ message: error.message });
    });
});

module.exports = router;
