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

export default apiHandler({
     get: getUserOrders
});

async function getUserOrders(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!' });

          if(userData.id != userID) 
               return res.status(401).json({ error: 'Unauthorized!'}); 

          const userOrders = await db.Orders.findAll({
               where: {
                    userID: userData.id 
               },
               order: [['id', 'DESC']] 
          }); 

          const responseArray = [];
          
          responseArray.push({ userOrders });

          return res.status(200).json(responseArray);
     } catch (error) {
          return res.status(500).json({ error: 'Eroare la preluarea datelor utilizatorului.' });
     }
}