import { db } from "@/helpers/api/db";

export default async function handler(req, res) {
     if (!db.initialized) {
          await db.initialize();
     }

     try {
          const { sku, orderID } = req.query;

          if (!sku || (!orderID && !isNaN(orderID))) {
               return res.status(400).json({ status: false, error: "Invalid request" });
          }

          const getOrderID = await db.Orders.findOne({
               attributes:['id'], 
               where: {
                    id: orderID 
               },
               raw: true, 
          });

          const productID = await db.Products.findOne({
               attributes:['id'], 
               where: { 
                    sku: sku, 
               },
               raw: true
          });

          if(!productID) {
               return res.status(200).json({ status: false, error: 'Produsul nu a putut fii identificat dupa codul SKU din comanda. Va rugam sa revizuiti.'}); 
          }

          if(!orderID) {
               return res.status(200).json({ status: false, error: 'Comanda nu a putut fii identificata dupa ID-ul introdus. Va rugam sa revizuiti.'}); 
          }

          const id = productID.id; 

          const selectedItems = { id }; 
          const selectedItemsJSON = JSON.stringify(selectedItems); 

          return res.status(200).json({ selectedItemsJSON, getOrderID, status: true });
     } catch (error) {
          console.error("Error fetching categories:", error);
          return res
               .status(500)
               .json({ error: "Internal server error", status: 500 });
     }
}
