const express = require("express");
const {db} = require("../config/dbConfig"); // assuming db.js is in the parent directory

const router = express.Router();

router.get("/api/products/top5", (req, res) => {
  try {
    // Query to fetch the top 5 products based on available stock (quantity > 0)
    const query = `
      SELECT 
        id,
        code,
        product_name,
        content,
        actual_price,
        price,
        quantity,
        photo_url
      FROM crackers
      WHERE quantity > 0
      ORDER BY id DESC
      LIMIT 10   
    `;

    db.query(query, (error, results) => {
      if (error) {
        console.error("Database error:", error);
        return res.status(500).json({
          success: false,
          message: "Error fetching products from database",
        });
      }

      // Check if results are empty
      if (results.length === 0) {
        return res.status(404).json({
          success: false,
          message: "No products found with available stock",
        });
      }

      // Format the results to ensure consistent structure
      const formattedResults = results.map((product) => ({
        id: product.id,
        code: product.code,
        product_name: product.product_name,
        content: product.content,
        actual_price: parseFloat(product.actual_price || 0),
        price: parseFloat(product.price || 0),
        quantity: product.quantity,
        photo_url: product.photo_url,
      }));

      // Return the formatted results
      res.status(200).json({
        success: true,
        message: "Top products fetched successfully",
        data: formattedResults,
      });
    });
  } catch (error) {
    console.error("Server error:", error);
    res.status(500).json({
      success: false,
      message: "Internal server error",
    });
  }
});

module.exports = router;
