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

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

     try {
          const {
               page = 1,
               limit = 32,
               sort = "newest",
               minPrice,
               maxPrice,
               category,
               search,
          } = req.query;

          const offset = (parseInt(page) - 1) * parseInt(limit);

          // Construim WHERE clause
          const whereClause = {};

          if (minPrice || maxPrice) {
               whereClause.price = {};
               if (minPrice) whereClause.price.$gte = parseFloat(minPrice);
               if (maxPrice) whereClause.price.$lte = parseFloat(maxPrice);
          }

          if (category) {
               whereClause.categoryId = category;
          }

          whereClause.priceReduced = { [Op.ne]: null };

          if (search) {
               whereClause.$or = [
                    { name: { $like: `%${search}%` } },
                    { description: { $like: `%${search}%` } },
               ];
          }

          whereClause.visible = 1; 
          whereClause.verified = 1; 

          // ORDER BY
          let orderClause = [["createdAt", "DESC"]];

          switch (sort) {
               case "price-asc":
                    orderClause = [["price", "ASC"]];
                    break;
               case "price-desc":
                    orderClause = [["price", "DESC"]];
                    break;
               case "name-asc":
                    orderClause = [["name", "ASC"]];
                    break;
               case "name-desc":
                    orderClause = [["name", "DESC"]];
                    break;
          }

          // QUERY OPTIMIZAT: findAndCountAll returnează {count, rows}
          const { count, rows: products } = await db.Products.findAndCountAll({
               where: whereClause,
               order: orderClause,
          
               offset: offset,
               attributes: ['id', 'name', 'name_en', 'name_de', 'name_it', 'name_fr', 'price', 'priceReduced', 'images', 'url', 'stock'], 
          });

          res.status(200).json({
               products,
               totalCount: count, // total produse din DB
               currentPage: parseInt(page),
               totalPages: Math.ceil(count / parseInt(limit)),
          });
     } catch (error) {
          console.error("Error fetching products:", error);
          res.status(500).json({
               error: "Eroare la încărcarea produselor",
          });
     }
}