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

export default apiHandler({
     post: addToCart,
     get: getCartProducts, 
     delete: deleteProductFromCart ,
});

async function deleteProductFromCart(req, res) {
     const userID = req.userID; 
     const productID = req.body; 
     
     if (!userID) {
          return res.status(400).json({ error: 'User ID is required' });
     }
 
     if (!db.initialized) 
         await db.initialize(); 
 
     try {
          const userData = await db.User.findByPk(userID); 
         
          if (!userData) 
               return res.status(404).json({ error: 'User not found' });
 
          if (isNaN(Number(productID.productID))) {
               return res.status(404).json({ error: 'Invalid product ID!'}); 
          }

          const cartData = await db.Cart.findByPk(productID.productID);

          if(!cartData) 
               return res.status(404).json({ error: 'No product found in carts.'}); 

          if(cartData.forID != userData.id)
               return res.status(404).json({ error: 'This product is not yours.'}); 

          await db.Cart.destroy({
               where: { id: productID.productID }
          });
 
          return res.status(200).json({ status: 200, message: 'Ai eliminat cu success acest produs din costul tau.' });
     } catch (error) {
          console.error(error); 
          return res.status(500).json({ error: 'Internal server error', status: 500 });
     }
}

async function getCartProducts(req, res) {
     const userID = req.userID; 
 
     if (!userID) {
          return res.status(400).json({ error: 'User ID is required' });
     }
 
     if (!db.initialized) 
         await db.initialize(); 
 
     try {
          const userData = await db.User.findByPk(userID); 
         
          if (!userData) 
               return res.status(404).json({ error: 'User not found' });
 
          const cartProducts = await db.Cart.findAll({ 
               where: {
                    forID: userID, 
               },
               raw: true, 
          });
 
          console.log(cartProducts);

          const productsDataPromises = cartProducts.map(async (product) => {
               const getProductAvatar = await db.Courses.findByPk(product.productID);
               product.avatar = (getProductAvatar) ? (getProductAvatar.previewImage):(null);
               product.url = (getProductAvatar) ? (getProductAvatar.url):(null);  

               return product;
          });
 
          const productsData = await Promise.all(productsDataPromises);
 
          return res.status(200).json({ cartProducts: productsData });
     } catch (error) {
          console.error(error); 
          return res.status(500).json({ error: 'Internal server error', status: 500 });
     }
 }

async function addToCart(req, res) {
     const userID = req.userID;
     const productData = req.body; 

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

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

          const getUserCart = await db.Cart.findOne({
               attributes: ['id'], 
               where: {
                    productID: productData.productID, 
                    forID: userID, 
               },
               raw:true, 
               limit: 1 
          });
          
          if(getUserCart) 
               return res.status(200).json({error: 'Acest articol se afla deja in cosul tau. Poti modifica cantitatea / sterge produsul din pagina cosului de cumparaturi.', status: 200});

          const cartData = {
               forID: userID, 
               productID: productData.productID, 
               restaurantID: productData.restaurantID, 
               productName: productData.productName,
               productQuantity: productData.userQantity,
               productPrice: productData.productPrice, 
               productPriceReduced: productData.productPriceReduced  
          };

          db.Cart.create(cartData); 

          return res.status(200).json({ message: 'Produsul a fost adaugat in cos cu succes !', status: 200 } );
     } catch (error) {
          return res.status(500).json({ error: 'Eroare la preluarea datelor utilizatorului.', status: 500 });
     }
}