const express = require('express');
const router = express.Router(); // eslint-disable-line new-cap
const jwt = require('jsonwebtoken');
const config = require('nconf');

const UserModel = require('../models/user');
const resHelpers = require('./helpers/response-helpers');

function getFutureDate(seconds) {
  const now = new Date();
  const future = new Date(now.getTime() + (seconds * 1000));
  return future.toISOString();
}

// Authenticate a user
router.post('/authenticate', (req, res) => {
  const { username, password } = req.body;

  UserModel.findOne({ username }, (err, user) => {
    if (err) {
      return res.json(resHelpers.error('Authentication error.'));
    }

    if (!user) {
      return res.json(resHelpers.fail(
        'Authentication not possible - username not found.',
        null,
        {
          validation: {
            username: {
              message: 'That username could not be found',
              value: username,
            },
          },
        }
      ));
    }

    user.comparePassword(password, (matchErr, isMatch) => {
      if (!isMatch) {
        return res.json(resHelpers.fail(
          'Authentication not possible.',
          null,
          {
            validation: {
              username: {
                value: username,
              },
              password: {
                message: 'The password is incorrect.',
              },
            },
          }
        ));
      }

      const payload = {
        id: user.id,
        username: user.username,
        name: user.name.full,
        role: user.role,
      };

      const expiresIn = req.body.remember ? 1209600 : 86400;

      const token = jwt.sign(payload, config.get('JWT:SECRET'), {
        expiresIn,
      });

      res.json(resHelpers.success(
        'Authentication successful.',
        {
          token,
          expires: getFutureDate(expiresIn),
          user: user.toObject({
            transform: (doc, ret) => {
              delete ret.__v; // eslint-disable-line no-param-reassign
              delete ret.password; // eslint-disable-line no-param-reassign
            },
          }),
        }
      ));
    });
  });
});

module.exports = router;

@@ -847,32 +847,30 @@
             
-username
+errors
 : %7B%0A        
@@ -871,30 +871,31 @@
             
-messag
+usernam
 e: 'That use
@@ -929,32 +929,62 @@
             
-  value:
+%7D,%0A            values: %7B%0A             
  username,%0A 
@@ -1270,24 +1270,22 @@
         
-username
+errors
 : %7B%0A    
@@ -1300,23 +1300,46 @@
     
-value: username
+password: 'The password is incorrect.'
 ,%0A  
@@ -1367,24 +1367,22 @@
         
-password
+values
 : %7B%0A    
@@ -1397,45 +1397,16 @@
     
-message: 'The password is incorrect.'
+username
 ,%0A  

split validation errors and values