const User = require("../../models").users
const Activity = require("../helpers/activity.helper")
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs');
const Op = require("sequelize").Op;
const CryptoJS = require("crypto-js");
const secretKey = "4gt71TxD1e4P3433";
var key = CryptoJS.enc.Base64.parse("4gt71TxD1e4P3433");
var iv  = CryptoJS.enc.Base64.parse("4gt71TxD1e4P3433");

exports.change = async (req, res) => {
try {

  const {
    PasswordCurrent,
    NewPassword,
    confirmNewPassword,
    username
  } = req.body

  if (NewPassword != confirmNewPassword) {
    return res.send({
              statusCode: "409",
              success: false,
              message: 'Error',
              error: 'not match'
          })
}
  const user = await User.findOne({
            where: {
                id: username
            }
        })
  if(!user){
    return res.send({
      statusCode: "409",
      success: false,
      message: 'Error',
      error: 'user not found'
  })
  } 
  var decrypted = (CryptoJS.AES.decrypt(user.password, key, {iv: iv})).toString(CryptoJS.enc.Utf8);
  const match = decrypted === PasswordCurrent;

  if (!match) {
      return res.send({
                statusCode: "409",
                success: false,
                message: 'Error',
                error: 'Invalid password'
            })
  } 
  
      const hashedpass = CryptoJS.AES.encrypt(NewPassword, key, {iv: iv}).toString();

      const updatePass = {
          password: hashedpass
        }

      const saveActivity = await Activity("password", "You change your password", username)

        //update pin
        const updateNewPass =   await User.update(updatePass, {
            where: {
              id:username
            }
          })
          if(!updateNewPass){
            return res.status(409).send({
              statusCode: "409",
              success: false,
              message: 'An error ocurred, try again'
          })
          }    

          return res.status(200).send({
            statusCode: "200",
            success: true,
            message: 'Password successfully changed'
        }) 
 
} catch(e) {
  console.log(e)
  res.status(500).send({
    statusCode: "500",
    success: false,
    message: "Error",
    error: e.message
})
}
}