const bcrypt = require('bcrypt');

import { csrf } from 'src/lib/csrf';
import { Auth } from './model';

function sessionGenerate() {
  return 'obvoiusly_this_is_a_complicated_session_key_' + Math.floor(Math.random() * 999);
}

function compareAsync(param1, param2) {
  return new Promise(function (resolve, reject) {
    bcrypt.compare(param1, param2, function (err, res) {
      if (err) {
        reject(err);
      } else {
        resolve(res);
      }
    });
  });
}

async function login(req) {
  return new Promise(async (res, rej) => {
    let { username: incoming_username, password: incoming_password } = JSON.parse(req.body);

    Auth.findOne({ where: { username: incoming_username } })
      .then(user_found => compareAsync(incoming_password, user_found.password))
      .then(async cmp_result => {
        if (cmp_result) {
          let session = sessionGenerate();
          let user_found = await Auth.update({ session }, { where: { username: incoming_username } });

          if (user_found.role == 'admin') {
            console.log('admin login OK');
            return res({ status: 'admin login OK', session, username: incoming_username });
          }

          console.log('customer login OK');
          return res({ status: 'customer login OK', session, username: incoming_username });
        } else {
          rej({ status: 'error' });
        }
      })
      .catch(err => {
        console.log('Auth.findOne err:', err);
        rej({ status: 'error' });
      });
  });
}

async function handler(req, res) {
  try {
    let result = await login(req);

    return res.status(200).send(result);
  } catch (err) {
    console.log(err);
    res.status(200).send({ status: 'error', message: 'helloworld error' });
  }
}

export default csrf(handler);
