const mongoose = require("mongoose");
const Category = mongoose.model("amazonCategory");

// Utility function to generate slug from text
const slugify = (text) =>
  text
    .toString()
    .toLowerCase()
    .trim()
    .replace(/[\s\W-]+/g, '-')     // Replace spaces & non-word chars with hyphens
    .replace(/^-+|-+$/g, '');      // Trim leading/trailing hyphens

// Recursive formatter for subCategories
const formatSubCategory = (subCategory = []) => {
  return subCategory
    .filter(sub => sub.name) // Ensure name exists
    .map(sub => {
      const formattedSubCategories = Array.isArray(sub.subCategory) && sub.subCategory.length > 0
        ? formatSubCategory(sub.subCategory)
        : [];

      const base = {
        name: sub.name,
        image: sub.image || null,
        slug: slugify(sub.name),
      };

      if (formattedSubCategories.length > 0) {
        base.subCategories = formattedSubCategories;
      }

      return base;
    });
};

// Controller to get all categories
exports.getAllCategories = async (req, res) => {
  try {
    const categories = await Category.find({});

    if (!categories.length) {
      return res.status(404).json({ success: false, message: "No categories found" });
    }

    const formattedCategories = categories.map(cat => ({
      category: cat.category,
      image: cat.image || null,
      slug: slugify(cat.category),
      subCategories: formatSubCategory(cat.subCategory)
    }));

    res.status(200).json({ success: true, data: formattedCategories });
  } catch (error) {
    res.status(500).json({ success: false, message: `Server Error: ${error.message}` });
  }
};
