const express = require('express');
const jwt = require('jsonwebtoken');


async function checkAuthorization(req, res, repository, onVerified)
{
  var token;

  if (req.headers.authorization)
  {
    if (req.headers.authorization.split(' ')[0] !== 'Bearer')
    {
      res.sendStatus(400);
      return;
    }

    token = req.headers.authorization.split(' ')[1];
  }
  else if (req.cookies && req.cookies.adminToken)
  {
    token = req.cookies.adminToken;
  }
  else
  {
    res.sendStatus(403);
    return;
  }


  jwt.verify(token, config.jwtSecret, async (err, decoded) =>
  {
    try
    {
      if (err)
      {
        res.sendStatus(403);
        return;
      }

      if (decoded.userId)
      {
        var user = await repository.users.get(decoded.userId);
        if (user === null || !user.active)
        {
          res.sendStatus(403);
          return;
        }
        else
          await onVerified(user);
      }
      else
        res.sendStatus(400);
    }
    catch (e)
    {
      console.log(e);
      res.sendStatus(500);
    }
  });
}


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

  // Redirects to make Vue-router URLs less quirky
  router.get('/', (req, res) => { res.redirect(301, '/#/admin/') });

  router.use(async (req, res, next) =>
  {
    try
    {
      await checkAuthorization(req, res, repository, (user) =>
      {
        req.user = user;
        next();
      });
    }
    catch (err)
    {
      console.log(err);
    }
  });

  require('./status')(repository, router);
  require('./codes')(repository, router);
  require('./uploads')(repository, router);
  require('./users')(repository, router);

  return router;
}