const router = require('express').Router();
const getRedisValue = require('../helpers/redis.helpers.js').getRedisValue;
const setRedisValue = require('../helpers/redis.helpers.js').setRedisValue;
const getDatasetInfoFromES = require('../helpers/elasticsearch.helpers.js').getDatasetInfoFromES;
const printError = require('../helpers/logs.helpers.js').printError;

router.get('/ign', (req, res, next) => {
  req.headers['referer'] = 'grandlyon.com';
  req.app.locals.proxies.ign.web(req, res, {});
  return;
});

router.get('/wms*', (req, res, next) => {
  req.app.locals.proxies.authenticated.web(req, res, {});
  return;
});

router.get('/mvt*', async (req, res, next) => {
  
  // If no cookies then then we can't identify a user and directly proxy the request without credentials
  if (req.headers["x-anonymous-consumer"]) {
    req.app.locals.proxies.unauthenticated.web(req, res, {});
    return;
  }

  // Read the requested layer from the url
  const layer = req.query.LAYERS;

  if (!layer) {
    res.status(400).send({err: "Bad request, missing LAYERS parameter."})
    return;
  }

  const userRightsOnTheLayer = await getRedisValue(req.app.locals.config.redisSentinelHost, req.app.locals.config.redisSentinelPort, req.app.locals.config.redisGroupName, `map-mvt-${layer}-${req.headers['x-consumer-username']}`);

  if (userRightsOnTheLayer === 'true') {
    req.app.locals.proxies.authenticated.web(req, res, {});
    return;
  }

  if (userRightsOnTheLayer === 'false') {
    res.status(401).send({err: 'Unauthenticated, you don\'t have access to this layer'});
    return;
  }

  let source;

  try {
    source = await getDatasetInfoFromES(
      req.app.locals.config.elasticsearchUrl,
      layer,
      [
        "editorial-metadata.isSample",
        "editorial-metadata.isOpenAccess"
      ],
      req.headers.cookie,
    );
  } catch(err) {
    printError('/mvt', err);
    res.status(err.status).send(err);
    return;
  }

  const editorialMetadata = source['editorial-metadata'];

  if (!editorialMetadata.isOpenAccess && editorialMetadata.isSample) {
    await setRedisValue(req.app.locals.config.redisSentinelHost, req.app.locals.config.redisSentinelPort, req.app.locals.config.redisGroupName, `map-mvt-${layer}-${req.headers['x-consumer-username']}`, false, req.app.locals.config.redisUnauthorizedTTL);
    res.status(401).send();
    return;
  }

  await setRedisValue(req.app.locals.config.redisSentinelHost, req.app.locals.config.redisSentinelPort, req.app.locals.config.redisGroupName, `map-mvt-${layer}-${req.headers['x-consumer-username']}`, true, req.app.locals.config.redisAuthorizedTTL);

  req.app.locals.proxies.authenticated.web(req, res, {});
});

module.exports = router;