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 code = await repository.codes.get(req.body.code);
    if (code !== null)
    {
      jwt.sign({
        codeId: req.body.code,
        codeUserId: code.userId,
        codeExpirationTime: code.expirationDate !== null ? code.expirationDate.getTime() : null
      }, 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
      }, config.jwtSecret, (err, token) =>
      {
        if (err)
          res.sendStatus(500);
        else
          res.send(token);
      });
    }
    else
      res.sendStatus(403);
  }));

  return router;
}