const db = require("../models");
const Employee = db.employee;
const config = require("../config/auth.config");

var jwt = require("jsonwebtoken");
var bcrypt = require("bcryptjs");
const { splitSite } = require("../middlewares");

// Create and Save a new User
exports.login = (req, res) => {
  var condition = {};
  const emailUsername = req.body.emailUsername;
  console.log('emailUsername', emailUsername);
  if (emailUsername) {
    condition = { $or: [ 
      { email: emailUsername },
      { username: emailUsername }
    ]};
    condition = splitSite.splitSiteGet(req, condition);
    
    Employee.find(condition)
      .then(data => {
        if (data && data.length > 0) {
          if (data.length === 1 && bcrypt.compareSync(
            req.body.password,
            data[0].password
          ) && data[0]?.status === 'active') {
            var token = jwt.sign({id: data[0].id}, config.secret, {
              expiresIn: 86400 // 24 hours
            });
            res.send({
              accessToken: token,
              username: data[0].username,
              email: data[0].email,
              roles: data[0].roles,
              id: data[0].id,
              name: data[0].name,
              name_cn: data[0].name_cn
            } );
          } else {
            if (data[0].status !== 'active') {
              throw(Error('User is not activated'));
            } else {
              throw(Error('Email or Password Is Invalid'));
            }
          }
        } else {
          throw(Error('Email or Password Is Invalid'));
        }
      })
      .catch(err => {
        res.status(500).send({
          message:
            err.message || "Email Or Password Invalid"
        });
      });
  } else {
    throw(Error('email or username is required'));
  }
}