import Router from 'koa-router'
import passport from 'koa-passport'
import jwt from 'jsonwebtoken'
import config from '../../config/config'

const router = new Router({ prefix: '/auth' })


/**
 * @api {post} /auth Authenticate user
 * @apiVersion 1.0.0
 * @apiName AuthUser
 * @apiGroup Auth
 *
 * @apiParam {String} email User email.
 * @apiParam {String} password User password.
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 *
 * @apiSuccessExample {json} Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *       "user": {
 *          "username": "johndoe"
 *        },
 *       "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
 *     }
 *
 * @apiError UserNotFound The id of the User was not found.
 *
 * @apiErrorExample {json} Error-Response:
 *     HTTP/1.1 401 Unauthorized
 *     {
 *       "status": 401,
 *       "error": "Unauthorized"
 *     }
 */
router.post('/', async (ctx, next) =>
  passport.authenticate('local', (user) => {
    if (!user) {
      ctx.throw(401)
    }

    const token = jwt.sign({ id: user.id }, config.token)

    const response = user.toJSON()

    delete response.password
    delete response.salt

    ctx.body = {
      token,
      user: response
    }
  })(ctx, next)
)

export default router

@@ -315,24 +315,31 @@
 ng%7D 
-email User email
+username  User username
 .%0A *
@@ -367,16 +367,17 @@
 assword 
+ 
 User pas
@@ -397,57 +397,267 @@
 @api
-Success %7BString%7D firstname Firstname of the
+Example Example usage:%0A * curl -H %22Content-Type: application/json%22 -X POST -d '%7B %22username%22: %22johndoe@gmail.com%22, %22password%22: %22foo%22 %7D' localhost:5000/auth%0A *%0A * @apiSuccess %7BObject%7D   user           User object%0A * @apiSuccess %7BObjectId%7D user._id      
  User
-.
+ id
 %0A * 
@@ -681,39 +681,142 @@
 ng%7D 
-lastname  Lastname of the User.
+  user.name      User name%0A * @apiSuccess %7BString%7D   user.username  User username%0A * @apiSuccess %7BString%7D   token          Encoded JWT
 %0A *%0A
@@ -913,16 +913,92 @@
 ser%22: %7B%0A
+ *          %22_id%22: %2256bd1da600a526986cf65c80%22%0A *          %22username%22: %22foo%22%0A
  *      
@@ -1236,53 +1236,41 @@
 or U
-serNotFound The id of the User was not found.
+nauthorized Incorrect credentials
 %0A *%0A

Update auth docs