const config = require('../../config');
const express = require('Express');
const asyncHandler = require('express-async-handler');
const jwt = require('jsonwebtoken');


module.exports = (repository) =>
{
  var router = express.Router();

  router.post('/upload', asyncHandler(async (req, res) =>
  {
    if (!req.body.code)
    {
      res.sendStatus(400);
      return;
    }

    var userId = await repository.codes.findCodeUserId(req.body.code);
    if (userId !== null)
    {
      jwt.sign({
        code: req.body.code,
        codeUserId: userId
      }, config.jwtSecret, (err, token) =>
      {
        if (err)
          res.sendStatus(500);
        else
          res.send(token);
      });
    }
    else
      res.sendStatus(403);
  }));


  router.post('/login', asyncHandler(async (req, res) =>
  {
    if (!req.body.username || !req.body.password)
    {
      res.sendStatus(400);
      return;
    }

    var user = await repository.users.getLoginUser(req.body.username, req.body.password);
    if (user !== null)
    {
      jwt.sign({
        userId: user.id,
        auth: user.auth
      }, config.jwtSecret, (err, token) =>
      {
        if (err)
          res.sendStatus(500);
        else
          res.send(token);
      });
    }
    else
      res.sendStatus(403);
  }));

  return router;
}