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');
  //const refreshToken = req.header('x-refrtok');

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

  let noaut = false;

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

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

  const access = 'auth';

  return User.findByToken(token, access, true).then((ris) => {

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

    if (ris.code === server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED) {
      return Promise.reject(server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED);
    }

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

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

      return ris.user.save().then(() => {
        req.user = ris.user;
        req.token = token;
        // req.refreshToken = refreshToken;
        req.access = access;
        next(); // Esegui il codice successivo
      });
    }
    // tools.mylog('userid', user._id);

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

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

    const access = 'auth';

    return User.findByToken(token, access, false).then((ris) => {
      if (ris.code !== server_constants.RIS_CODE_OK) {
        req.user = null;
        req.token = null;
        req.access = null;
        req.code = ris.code;
      } else {
        req.user = ris.user;
        req.token = token;
        req.refreshToken = refreshToken;
        req.access = access;
        req.code = ris.code;
      }
      // Vai avanti ad eseguire il codice, in ogni modo !
      next();
    }).catch((e) => {
      req.user = null;
      req.token = null;
      req.access = null;
      req.code = 0;
      
      // Continua comunque !
      next();
    });
  } catch (e) {
    console.error('Err', e);
  }
};

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