const getDatasetInfoFromES = require('./elasticsearch.helpers.js').getDatasetInfoFromES;
const validateUserAccesses = require('./userAccesses.helpers.js').validateUserAccesses;
const getRedisValue = require('../helpers/redis.helpers.js').getRedisValue;
const setRedisValue = require('../helpers/redis.helpers.js').setRedisValue;

module.exports.requestProcessor = async (req, res, layer, service, pathToFile) => {
    const source = await getDatasetInfoFromES(
      req.app.locals.config.elasticsearchUrl,
      layer,
      [
        "editorial-metadata.isOpenAccess"
      ],
      req.headers.cookie,
      pathToFile
    );

    // If dataset is open access proxy the request without adding the technical account credentials
    if (source['editorial-metadata'].isOpenAccess) {
      req.app.locals.proxies.unauthenticated.web(req, res, {});
      return;
    }

    // If it is a restricted access layer and the user isn't authenticated then directly send a 401 error 
    if (!source['editorial-metadata'].isOpenAccess && req.headers['x-anonymous-consumer']) {
      throw {
        status: 401,
        message: "Unauthenticated, you need to be authenticated to access this resource."
      }
    }

    // Look for an existing value of the user rights for the layer in redis
    let userAccesses = await getRedisValue(req.app.locals.config.redisSentinelHost, req.app.locals.config.redisSentinelPort, req.app.locals.config.redisGroupName, `download-${layer}-${service}-${req.headers['x-consumer-username']}`);

    // If value found and true, proxy the request adding the technical account credentials
    if (userAccesses === 'true') {
      req.app.locals.proxies.authenticated.web(req, res, {});
      return;
    }

    // If value found and false, directly send a 403 forbidden error
    if (userAccesses === 'false') {
      throw {
        status: 403,
        message: "Forbidden access."
      }
    }

    // If no pre-existing value for that user, layer and service triple then check the user rights
    userAccesses = await validateUserAccesses(req.app.locals.config.legacyAuthMiddlewareUrl, req.headers, `${req.params.repo}/${layer}`, service);

    if(!userAccesses) {
      await setRedisValue(req.app.locals.config.redisSentinelHost, req.app.locals.config.redisSentinelPort, req.app.locals.config.redisGroupName, `download-${layer}-${service}-${req.headers['x-consumer-username']}`, false, req.app.locals.config.redisUnauthorizedTTL);
      throw {
        status: 403,
        message: "Forbidden access."
      }
    }

    await setRedisValue(req.app.locals.config.redisSentinelHost, req.app.locals.config.redisSentinelPort, req.app.locals.config.redisGroupName, `download-${layer}-${service}-${req.headers['x-consumer-username']}`, true, req.app.locals.config.redisAuthorizedTTL);
    req.app.locals.proxies.authenticated.web(req, res, {});
    return;
}