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


async function checkAuthorization(req, res, onVerified)
{
  if (!req.headers.authorization || req.headers.authorization.split(' ')[0] !== 'Bearer')
  {
    res.sendStatus(400);
    return;
  }

  var token = req.headers.authorization.split(' ')[1];
  jwt.verify(token, config.jwtSecret, async (err, decoded) =>
  {
    try
    {
      if (err)
      {
        res.sendStatus(403);
        return;
      }

      if (decoded.codeUserId)
        await onVerified(decoded);
      else
        res.sendStatus(400);
    }
    catch (e)
    {
      console.log(e);
      res.sendStatus(500);
    }
  });
}



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

  // Upload API
  router.post('/complete', asyncHandler(async (req, res) =>
  {
    if (!req.body.files)
    {
      res.sendStatus(400);
      return;
    }

    await checkAuthorization(req, res, async (decoded) =>
    {
      var expiration = null; // TODO set expiration properties
      var uploadId = await repository.uploads.addUpload(decoded.codeUserId, req.body.files, expiration);
      res.send({ id: uploadId });
    });
  }));


  // Tus upload
  const uploadApp = express();
  uploadApp.all('*', asyncHandler(async (req, res) =>
  {
    await checkAuthorization(req, res, async (decoded) =>
    {
      tusServer.handle(req, res);
    });
  }));

  router.use('/upload', uploadApp);
  return router;
}