module.exports = {
  lookup: function (req, res) {
    return Invitation.where({token: req.param('token')}).fetch({withRelated: 'community'})
    .then(invitation => {
      if (!invitation) {
        return res.ok({error: 'bad link'})
      }

      if (invitation.isUsed()) {
        return res.ok({error: 'used link'})
      }

      return res.ok(invitation.relations.community.pick('id', 'name', 'slug', 'avatar_url'))
    })
  },

  use: function (req, res) {
    return Invitation.where({token: req.param('token')}).fetch()
    .then(function (invitation) {
      if (!invitation) {
        return res.ok({error: 'bad link'})
      }

      if (invitation.isUsed()) {
        return res.ok({error: 'used link'})
      }

      // user is logged in; apply the invitation
      if (UserSession.isLoggedIn(req)) {
        return bookshelf.transaction(trx => {
          return invitation.use(req.session.userId, {transacting: trx})
          .then(invitation =>
            Post.createWelcomePost(req.session.userId, invitation.get('community_id'), trx))
        })
        .then(() => res.ok({}))
        .catch(err => {
          if (err.message && err.message.contains('duplicate key value')) {
            return res.ok({error: 'already a member'})
          } else {
            throw err
          }
        })
      }

      // return invitation data so that the front-end can store it
      // and re-use it after completing signup or login
      return invitation.load('community').then(function () {
        req.session.invitationId = invitation.id
        res.ok(_.merge(invitation.toJSON(), {
          signup: true
        }))
      })
    })
    .catch(res.serverError)
  }

}

@@ -205,38 +205,44 @@
 urn res.
-ok(%7Berror: 'bad link'%7D
+status(422).send('bad token'
 )%0A      
@@ -296,39 +296,45 @@
 urn res.
-ok(%7Berror: 'used link'%7D
+status(422).send('used token'
 )%0A      
@@ -618,30 +618,36 @@
 res.
-ok(%7Berror: 'bad link'%7D
+status(422).send('bad token'
 )%0A  
@@ -709,31 +709,37 @@
 res.
-ok(%7Berror: 'used link'%7D
+status(422).send('used token'
 )%0A  
@@ -1237,28 +1237,27 @@
   re
-turn res.ok(%7Berror: 
+s.status(422).send(
 'alr
@@ -1270,17 +1270,16 @@
  member'
-%7D
 )%0A      

use 422 error codes in InvitationController