var User = require('../models/user');
var AuthToken = require('../models/auth-token');

var auth = require('../lib/auth');
var crypto = require('crypto');

module.exports = function(db) {
  return {
    token: function(req, res) {
      var username = req.body['username'];
      var password = req.body['password'];

      if (typeof username === 'undefined' || typeof password == 'undefined') {
        return res.send(401, 'Missing arguments');
      }

      var user = User.findOne({username: username}, function(err, user) {
        if (err || user == null) {
          return res.send(401, 'User not found');
        }

        if (auth.comparePassword(password, user.password)) {
          var key = crypto
            .createHash('sha1')
            .update(user.username + user.password + Date.now().toString())
            .digest('hex');

          var token = new AuthToken({ token: key, userId: user._id });

          token.save(function(err, authToken) {
            if (err) {
              return res.send(401, err);
            }

            res.json(200, {
              user: user,
              token: authToken.token
            });
          });
        } else {
          return res.send(401, 'Not authorized');
        }        
      });
    },
    validate: function(req, res) {
      var token = req.body['token'];

      if (typeof token === 'undefined') {
        return res.send(401, 'Missing arguments');
      }

      var authToken = AuthToken.findOne({token: token}, function(err, authToken) {
        if (err || authToken == null) {
          return res.send(401, 'Invalid session token');
        }

        var user = User.findOne({_id: authToken.userId}, function(err, user) {
          return res.json(200, {
            token: authToken.token,
            user: user
          });
        });
      });
    },
    invalidate: function(req, res) {
      var token = req.body['token'];

      if (typeof token === 'undefined') {
        return res.send(401, 'Missing arguments');
      }

      AuthToken.findOneAndRemove({token: token}, function(err) {
        if (err) {
          return res.send(401, 'Invalid session token');
        }

        return res.json(200);
      });
    }
  }
};
