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);
}

async function hashPassword(plainTextPassword) {
  const saltRounds = 10;
  return await bcrypt.hash(plainTextPassword, saltRounds);
}

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 ChangePassword(req) {
  return new Promise(async (res, rej) => {
    let { username, old_password, new_password } = JSON.parse(req.body);
    let new_password_hashed = await hashPassword(new_password);
    console.log({ username, old_password, new_password });

    Auth.findOne({ where: { username } })
      .then(user_found => compareAsync(old_password, user_found.password))
      .then(compare_result => {
        console.log({ compare_result });
        if (compare_result) {
          return Auth.update({ password: new_password_hashed }, { where: { username }, limit: 1 });
        } else {
          throw new Error('wrong password');
        }
      })
      .then(() => {
        res({ status: 'password change ok' });
      })
      .catch(err => {
        console.log('Auth.findOne err:', err);
        rej({ status: 'password change error' });
      });
  });
}

async function handler(req, res) {
  try {
    let result = await ChangePassword(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);
