module.exports = function(connection) {
  const Model = require('./user.model')(connection);

  return {
    get(req, res) {
      const { username } = req.query;

      if (username != null || username != '') {
        return Model
          .find()
          .byUsername(username)
          .then(user => res
            .status(200)
            .json(user))
          .catch(({ message }) => res
            .status(404)
            .json({ message }));
      } else {
        return res
          .status(404)
          .json({
            message: 'Query should contain valid username only'
          });
      }
    },

    create(req, res) {
      return Model
        .find()
        .byUsername(req.body.username)
        .then(user => user != null && res
          .status(409)
          .json({
            message: `User with username "${ req.body.username }" already exsist`
          }))
        .catch(err => Model.create(req.body))
        .then(user => res
          .status(200)
          .json({
            message: 'User successfully created'
          }))
        .catch(err => res
          .status(500)
          .json({
            message: 'Unable to create user',
            log: err.message
          }))
    },

    update(req, res) {
      const { username } = req.query;

      if (username == null || username == '') {
        return res
          .status(400)
          .json({
            message: 'Cannot update anything without an username'
          });
      } else {
        return Model
          .findOneAndUpdate({ username }, req.body, { new: true })
          .exec()
          .then(data => res
            .status(200)
            .json({
              message: 'Successfully updated'
            }))
          .catch(err => res
            .status(500)
            .json({
              message: 'Something wrong happend during updating an user'
            }));
      }
    }
  }
}
