const server_constants = require('../tools/server_constants');

var { User } = require('../models/user');

const tools = require('../tools/general');

const auth_default = (req, res, next) => {

  if (req.body.keyappid === process.env.KEY_APP_ID)
    next();

};

const authenticate = (req, res, next) => {
  const token = req.header('x-auth');

  // console.log('authenticate... ');

  let noaut = false;

  if (req.body.hasOwnProperty('noaut')) {
    noaut = req.body.noaut;
  }

  if (noaut) {
    next();
    return;
  }

  const access = 'auth';

  User.findByToken(token, access).then((user) => {

    if (!user) {
      // tools.mylog("TOKEN " + token);
      // tools.mylog(" NOT FOUND! (Maybe Connected to other Page) ACCESS: '" + access + "'");
      return Promise.reject(server_constants.RIS_CODE_HTTP_INVALID_TOKEN);
      // res.status().send();
    }

    if (!!user.deleted) {
      if (user.deleted)
        user = null;
    }

    if (!user) {
      return Promise.reject(server_constants.RIS_CODE_HTTP_INVALID_TOKEN);
    }

    if (!!user) {
      // Save last time online
      user.lasttimeonline = new Date();
      user.useragent = req.get('User-Agent');

      return user.save().then(() => {
        req.user = user;
        req.token = token;
        req.access = access;
        next();
      });
    }
    // tools.mylog('userid', user._id);

  }).catch((e) => {
    tools.mylog("ERR authenticate invalid Token =", e);
    res.status(server_constants.RIS_CODE_HTTP_INVALID_TOKEN).send();
  });
};

const authenticate_noerror = (req, res, next) => {
  const token = req.header('x-auth');

  const access = 'auth';

  User.findByToken(token, access).then((user) => {
    if (!user) {
      req.user = null;
      req.token = null;
      req.access = null;
    } else {
      req.user = user;
      req.token = token;
      req.access = access;
    }
    next();
  }).catch((e) => {
    req.user = null;
    req.token = null;
    req.access = null;
  });
};

module.exports = { authenticate, authenticate_noerror, auth_default };
