const path = require( 'path' );

// Check if package is installed or not to pickup the right config file
//const src = ( __dirname.indexOf( '/node_modules/' ) > -1 ) ? '../../..' : '..';
//const config = require( path.normalize( `${__dirname}/${src}/config.js` ) );
const config = require( '../tribes/townconf.js' );
/*
Check que le header contient des éléments necessaire pour les
routes utilisant tribeid / language / token / uuid
*/
const checkHeaders = ( req, res, next ) => {
	//logger.info( 'checkHeaders()' );
	// These headers must be passed in the request
	// X-Auth and X-Uuid could have any true value
	// header is stored in req.app.locals.header to be pass to route
	/*  const header = {
	  xtribeid: req.header('x-client-id'),
	  xlang: req.header('x-language'),
	  xauth: req.header('x-auth'),
	  xuuid: req.header('x-uuid'),
	  xworkon: req.header('x-xorkon',
	  xapp:req.header('x-app'))
	};
	On recupere accessrights via is Authenticated
	*/
	req.session = {};
	const header = {};
	let missingheader = "";
	//logger.info( 'avant validation headers', req.headers );
	//attention changement 7/11/2021 phil des exposedheader cf config.js
	//If in httprequest url header are send then they are used inpriority
	//Use case : send an email with a unique link that works without password and request to change password
	for( const h of config.exposedHeaders ) {
		//logger.info( h, req.header( h ) )
		if( req.params[ h ] ) {
			header[ h ] = req.params[ h ]
		} else if( req.header( h ) ) {
			header[ h ] = req.header( h )
		} else {
			// Missing header
			missingheader += " " + h
		}
	};
	//logger.info( 'header', header )
	if( req.params.xauth && req.params.xuuid ) {
		// If this exist => it is a timeout limited token
		req.app.locals.tokens[ req.params.xpaganid ] = req.params.xauth;
	}
	req.session.header = header;
	// Each header have to be declared
	if( missingheader != "" ) {
		return res.status( 403 )
			.send( {
				info: [ 'forbiddenAccess' ],
				model: 'Pagans',
				moreinfo: 'checkHeader headerIsMissing:' + missingheader
			} );
	};
	//logger.info( req.app.locals.tribeids )
	if( !req.app.locals.tribeids.includes( header.xtribe ) ) {
		return res.status( 404 )
			.send( {
				info: [ 'tribeiddoesnotexist' ],
				model: 'Pagans',
				moreinfo: `xtribe unknown: ${header.xtribe}`
			} );
	}
	if( !req.app.locals.tribeids.includes( header.xworkon ) ) {
		return res.status( 404 )
			.send( {
				info: [ 'tribeiddoesnotexist' ],
				model: 'Pagans',
				moreinfo: `xworkon unknown: ${header.xworkon}`
			} );
	}
	if( !config.languagesAvailable.includes( header.xlang ) ) {
		return res.status( 404 )
			.send( {
				info: [ 'langNotused' ],
				model: 'Pagans',
				moreinfo: `xlang unknown: ${header.xlang}`
			} );
	}
	//logger.info( 'After middleare checkHeaders.js req.session.header', req.session.header )
	//logger.info( 'checkheaders next' )
	next();
};
module.exports = checkHeaders;
