'use strict';

const passport = require('passport');
const httpStatus = require('http-status');
const compose = require('../helpers/middleware.helper');

const isRegisteredUserEmail = passport.authenticate('local-email', { session: false });
const isRegisteredUserPhone = passport.authenticate('local-phone', { session: false });
const isLoggedUser = passport.authenticate('jwt', { session: false });
const isAPIKeyUser = passport.authenticate('api-key', { session: false });

const isOptionalUser = (req, res, next) => {
    const token = ((req && req.headers && req.headers['x-access-token']) ? req.headers['x-access-token'] : null);
    if (token) {
        isLoggedUser(req, res, next)
    } else {
        next();
    }
}

const isAdministratorUser = compose([isLoggedUser,
    (req, res, next) => {
        const user = req.user;
        if (user.level >= 8) {
            next();
        } else {
            return res.status(httpStatus.UNAUTHORIZED).send('Unauthorized. User is not administrator.');
        }
    }
]);

module.exports = {
    isRegisteredUserEmail,
    isRegisteredUserPhone,
    isLoggedUser,
    isOptionalUser,
    isAdministratorUser,
    isAPIKeyUser
};