const axios = require('axios').default;
const debug = require('debug')('developer:note');



async function getUserForLoginData(email, password) {
  const response = await axios({
    method: 'post',
    url: process.env.backend_url+'/api/auth/local',
    data: {
      identifier: email,
      password: password
    }
  }).catch(e=>console.log('error',"Error login!"));
  if(response && response.data){
    var user =  response.data;
    var userData = await getUser(user.jwt);
    return {
      id: user.user.id,
      name:user.user.username,
      username: user.user.email,
      jwt:user.jwt,
      role: userData.role,
      company: userData.company!= null?userData.company.id:null,
      division: userData.division != null?userData.division.id:null
    };
  }
  return null;
}

async function getUser(token) {
  if(token){
    const response = await axios({
      method: 'get',
      url: process.env.backend_url+'/api/users/me',
      headers: {'Authorization': 'Bearer '+token},
    }).catch(e=>console.log('error',"Error login!"));
    if(response && response.data){
      var user = response.data;
      return user;
    }
  }
  
  return null;
}

async function getUserById(id,token) {
  return getUser(token);
}

module.exports = {
  getUserForLoginData,
  getUserById,
};
