 koding                 = require './../bongo'
 async                  = require 'async'
 
-{ isLoggedIn }         = require './../helpers'
 { generateFakeClient } = require './../client'
+{ isLoggedIn, generateAPIError } = require './../helpers'
 
 # handleTokenedRequest handles the request if it has a token as query param,
 # fetchMembers is secured by a permission, that can be turned off by default,
 # but we want to show latest members to invited user
-handleTokenedRequest = (params, res, next) ->
+handleTokenedRequest = (params, callback) ->
 
   { JGroup, JInvitation }           = koding.models
   { name, options, token, client }  = params
 
-  group = null
+  group   = null
+  members = null
 
   queue = [
 
     (next) ->
-      return res.status(403).send 'not authorized'  unless token
+      return next generateAPIError 403, 'not authorized'  unless token
 
       # fetch invitation
       JInvitation.byCode token, (err, token_) ->
-        return res.status(403).send 'not authorized'  if err or not token_
+        return next generateAPIError 403, 'not authorized'  if err or not token_
         next()
 
     (next) ->
       # fetch the group that we have in token
       JGroup.one { slug : name }, (err, group_) ->
-        return res.status(500).send 'an error occured'  if err
-        return res.status(404).send 'no group found'    unless group_
+        return next generateAPIError 403, 'an error occured'  if err
+        return next generateAPIError 404, 'no group found'    unless group_
 
         group = group_
         # override group name with the one in token

      options.sort  = { 'meta.createdAt' : -1 }
      options.limit = Math.min limit ? 10, 25

      group.fetchMembers$ client, {}, options, (err, members) ->

        if err and err.message is 'Access denied'
          params = { name, client, options, token }
          return handleTokenedRequest params, res, next
        else if err
          return res.status(500).send 'an error occured'
        else
          return res.status(200).send members

  ]

  async.series queue

  { limit, token }  = query
  { JGroup }        = koding.models

  group   = null
  client  = null
  members = null

  queue = [

    (next) ->
      isLoggedIn req, res, (err, loggedIn, account) ->
        return next generateAPIError 500, 'an error occured'  if err
        next()

    (next) ->
      JGroup.one { slug : name }, (err, group_) ->
        return next generateAPIError 500, 'an error occured'  if err
        return next generateAPIError 404, 'no group found'    unless group_
        group = group_
        next()

    (next) ->
      generateFakeClient req, res, (err, client_) ->
        return next generateAPIError 500, 'an error occured'  if err
        client = client_
        next()

