const User = require("../../models").users
const Activity = require("../helpers/activity.helper")
const Token = require("../../models").tokens
const bcrypt = require('bcrypt');
const restMail = require("../helpers/passwordResetMailer")
const codeGenerator = require("../helpers/codeGenerator.helper")
const CryptoJS = require("crypto-js");
var key = CryptoJS.enc.Base64.parse("4gt71TxD1e4P3433");
var iv  = CryptoJS.enc.Base64.parse("4gt71TxD1e4P3433");

exports.code = async (req, res) => {
try {
  var {
    username
  } = req.body
 
  if (!username) {
    return res.status(409).send({
      statusCode: "409",
      success: false,
      message: 'Error',
      error: 'Username is required'
  })
  }

  let user = await User.findOne({
      where: {
        username
      }
    })
    user = JSON.parse(JSON.stringify(user))
    if(!user){
      return res.status(409).send({
        statusCode: "409",
        success: false,
        message: 'Error',
        error: 'Error, Account doesn\'t exist with your email address'
      })
    }
    if (!user.email) {
      return res.status(409).send({
        statusCode: "409",
        success: false,
        message: 'Error',
        error: 'No email found'
    })
    }

var decrypted = (CryptoJS.AES.decrypt(user.password, key, {iv: iv})).toString(CryptoJS.enc.Utf8);
console.log(decrypted)
const saveActivity = await Activity("password", "Request to change password with reset code", user.username)
 
   const sendRestEmail = restMail(user.email, user.username, decrypted);
   if(saveActivity && sendRestEmail){
     
     return res.status(200).send({
       statusCode: "200",
       success: true,
       message: "Success",
       message: 'Password reset code successfully sent'
     })
   }


} catch (e){
  res.status(500).send({
    statusCode: "500",
    success: false,
    message: "Error",
    error: e.message
})
}
}