const conf = require(`${process.env.dirtown}/conf.json`);

const checkHeaders = (req, res, next) => {
  /**
   * @apiDefine apxHeader
   * @apiGroup Middleware
   * @apiDescription Header is mandatory to access apxtrib see tribes/townconf.json.exposedHeaders
   * A turn around can be done with a simple get params has to be sent in the get url. Usefull to send simple get without header like ?xworkon=tribeName&xlang=en... priority is given to headers
   * For performance, tokens are store globaly in req.app.locals.tokens={xpaganid:xauth}
   * if xlang is not in conf.languagesAvailable
   *
   * @apiHeader {string} xjwt Pagans unique jwt token store in local town Pagans data or "noauth"
   * @apiHeader {string} xpseudo Pagans unique Pagan id in uuid format or "nouuid"
   * @apiHeader {string} xlang the 2 letter langage it request the api (if not exist the 2 first letter of Accept-Language header ) if lang does not exist in the town then en is set (as it always exist in en).
   * @apiHeader {string} xtribe Tribes id where pseudo want to act
   * @apiHeader {string} xapp Name of www/xapp folder that host app that send the request
   *  /tribeid/person/xpseudo.json have accessright on this app store in /tribe/tribeid/www/xapp
   *
   * @apiError missingexposedHeaders it miss an exposedHeaders
   *
   * @apiErrorExample {json} Error-Response:
   * 	HTTP/1/1 400 Not Found
   * 		{
   * 			status:400,
   * 			ref:"headers"
   * 			msg:"missingheaders",
   *            data: ["headermissing1"]
   *      }
   *@apiErrorExample {json} Error-Response:
   * 	HTTP/1/1 404 Not Found
   * 		{
   * 			status:404,
   * 			ref:"headers"
   * 			msg:"tribeiddoesnotexist",
   *            data: {xalias}
   *      }
   *
   * @apiHeaderExample {json} Header-Exemple:
   *     {
   * 		  xtribe:"apache",
   *          xalias:"toto",
   *          xhash:"",
   * 		  xdays:"123"
   *          xlang:"en",
   *          xapp:"popular"
   * 		}
   */
  req.session = {};
  const header = {};
  if (!req.header("xlang") && req.header("Content-Language"))
    req.params.xlang = req.header("Content-Language");
  let missingheader = [];
  //console.log("req.headers", req.headers);
  for (const h of conf.api.exposedHeaders) {
    //console.log( h, req.header( h ) )
    if (req.params[h]) {
      header[h] = req.params[h];
    } else if (req.header(h)) {
      header[h] = req.header(h);
    } else {
      missingheader.push(h);
    }
  }
  //console.log( 'header', header )
  // store in session the header information
  req.session.header = header;
  // Each header have to be declared
  if (missingheader != "") {
    // bad request
    return res.status(400).json({
      ref: "headers",
      msg: "missingheader",
      data: missingheader,
    });
  }
  //console.log( req.app.locals.tribeids )
  // xtribe == "town" is used during the setup process
  if (
    !(
      header.xtribe == "town" || req.app.locals.tribeids.includes(header.xtribe)
    )
  ) {
    return res.status(404).json({
      ref: "headers",
      msg: "tribeiddoesnotexist",
      data: { xtribe: header.xtribe },
    });
  }
  if (!conf.api.languages.includes(header.xlang)) {
    console.log("warning language requested does not exist force to english");
    header.xlang = "en";
  }
  next();
};
module.exports = checkHeaders;
