import { apiHandler, db } from '@/helpers/api';
import bcrypt from 'bcryptjs';

export default apiHandler({
     post: newPassword
});

async function newPassword(req, res) {
     const userID = req.userID;
     const formData = req.body; 

     if(!db.initialized)
          await db.initialize(); 

     try {
          const userData = await db.User.findByPk(userID, {
               attributes: ['hash']
          });
          
          if (!userData) 
               return res.status(404).json({ error: 'Unknown!' });

          const cryptedRetype = bcrypt.hashSync(formData.retypePassword, 10); 

          if (!bcrypt.compareSync(formData.currentPassword, userData.hash)) 
               return res.status(201).json({ error: 'Parola curenta introdusa de tine nu este acceasi cu a contului tau.'}); 
          
          if(!bcrypt.compareSync(formData.newPassword, cryptedRetype))
               return res.status(201).json({ error: 'Parola noua nu este scrisa la fel in ambele locuri. '}); 

          return res.status(200).json({ message: 'Felicitari! Parola a fost actualizata cu succes.' });
     } catch (error) {
          return res.status(500).json({ error: 'Unexpected Error!' });
     }
}