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

export default apiHandler({
     delete: deleteUserAccount
});

async function deleteUserAccount(req, res) {
     const userID = req.userID;

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

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

          await db.Orders.destroy({ where: { userID: userData.id }}); 
          await db.Returns.destroy({ where: { userID: userData.id } }); 
          await db.Returns.destroy({ where: { userID: userData.id }}); 

          await userData.destroy(); 

          return res.status(200).json({ message: 'Contul a fost șters cu succes.' });
     } catch (error) {
          return res.status(500).json({ error: 'Eroare la preluarea datelor utilizatorului.' });
     }
}