const SubSubCatagory = require("../models/SubSubCatagory");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const ejs = require("ejs");
const path = require("path");
const { success } = require("concurrently/src/defaults");

exports.postNew = async function (req, res) {
  console.log("nnnnnn", req.body);
  try {
    const dataArray = req.body;
    if (!Array.isArray(dataArray)) {
      return res.status(422).json({
        message: "Data should be an array",
      });
    }
    await SubSubCatagory.insertMany(dataArray);

    res.status(200).json({ message: "Success" });
  } catch (error) {
    console.log("Error: ", error);
    res.status(500).json({ success: false, message: "Internal server error" });
  }
};

exports.AddSubCat = async function (req, res) {
  console.log("nnnnnn", req.body);
  const { subcatagory, imageSubCatagory, catagory } = req.body;

  if (!subcatagory || !imageSubCatagory || !catagory) {
    return res.status(422).json({
      message: "All feilds are required",
    });
  }
  try {
    const subcatagorie = new SubSubCatagory({
      subcatagory: subcatagory,
      imageSubCatagory: imageSubCatagory,
    });
    const subsubcatagories = await subcatagorie.updateOne({ _id: catagory });
    res.status(200).json({ message: "success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};


exports.updateEditedData = async function (req, res) {
  console.log("nnnnnn", req.params.id);
  console.log("ody-====", req.body)
  let body = req.body;

  try {
    const id = req.params.id;
    const access = await SubSubCatagory.findOne({ _id: id });
    if (access.SKU !== '0' && access.SKU !== 0) {
      const updatedSubSubCategories = await SubSubCatagory.updateMany(
        { SKU: access.SKU },
        { $set: body }
      );
      res.status(200).json({ message: "success", updatedSubSubCategories });
    } else {
      const subsubcatagories = await SubSubCatagory.updateOne({ _id: req.params.id }, body);
      res.status(200).json({ message: "success", subsubcatagories });
    }
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};


exports.EditedDataimage = async function (req, res) {
  console.log("nnnnnn", req.params.id);
  console.log("nnnnnn", req.params.index);
  let id = req.params.id;
  let index = req.params.index;
  let body = req.body;
  console.log("ody-====", body.imageSubsubCatagory[0]);
  try {
    // First, find the document
    let document = await SubSubCatagory.findById(id);

    if (!document) {
      return res.status(404).json({ success: false, message: "Document not found" });
    }

    // Update the array element at the specified index
    document.imageSubsubCatagory[index] = body.imageSubsubCatagory[0];

    // Save the updated document
    await document.save();

    res.status(200).json({ message: "success" });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(500).json({ success: false, message: error.message });
  }
};


exports.updateEditedDataimage = async function (req, res) {
  // console.log("nnnnnn", req.params.id);
  let body = req.body;
  console.log("ody-====", body.imageSubsubCatagory[0]);

  try {
    const subsubcatagories = await SubSubCatagory.updateOne(
      { _id: req.params.id },
      { $push: { imageSubsubCatagory: body.imageSubsubCatagory[0] } }
    );
    res.status(200).json({ message: "success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};



exports.updateEditedDataNewDb = async function (req, res) {
  console.log("nnnnnn", req.params.id);
  console.log("ody-====", req.body);
  let body = req.body;

  try {
    const subsubcatagories = await SubSubCatagory.updateOne(
      { _id: req.params.id },
      { $push: { reviews: { $each: body.reviews } } }, // Use $push to append new reviews
      { new: true, upsert: true }
    );
    res.status(200).json({ message: "success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};




exports.updateshowHideStatus = async function (req, res) {
  console.log("nnnnnn", req.params.id);
  console.log("ody-====", req.body)
  let body = req.body;

  try {
    const subsubcatagories = await SubSubCatagory.updateOne({ _id: req.params.id }, body);
    res.status(200).json({ message: "success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};


exports.GetAllCatagoryDD2 = async function (req, res) {
  const page = parseInt(req.params.page) || 1; // Default Page
  const limit = parseInt(req.params.limit) || 40; // Default Number

  try {
    const skip = (page - 1) * limit;

    const subsubcatagories = await SubSubCatagory.find({})
      .sort({ createdAt: -1 }) // To solve problem of new added products first
      .skip(skip)
      .limit(limit);

    const totalProducts = await SubSubCatagory.countDocuments();

    const totalPages = Math.ceil(totalProducts / limit);

    res.status(200).json({
      success: true,
      message: "Success",
      limit,
      page,
      subsubcatagories: subsubcatagories,
      totalPages: totalPages,
      totalProducts: totalProducts
    });
  } catch (error) {
    console.log("Error:", error);
    res.status(500).json({ success: false, message: "Internal Server Error" });
  }
};



exports.GetAllCatagoryDD = async function (req, res) {
  console.log("abc=1====", req.params.id);
  let searchQuery = req.params.id;
  try {
    const subsubcatagories = await SubSubCatagory.find();
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};

exports.UpdateSSC = async function (req, res) {
  console.log("abc=1====", req.params.id);
  try {
    const data = req.body; // Assuming the data sent from the frontend is in the request body
    console.log("Abc=====", data)
    const subsubcatagories = await SubSubCatagory.find();
    console.log("subsubcatagories=====", subsubcatagories)

    if (data.length === 1) {
      // Update if the length of the array is 1
      const subsubcat = await SubSubCatagory.findById(req.params.id);
      if (subsubcat && subsubcat.SKU !== "0" && subsubcat.SKU !== 0) {
        await SubSubCatagory.updateMany({ SKU: subsubcat.SKU }, data[0]);
        return res.status(200).json({ message: "Success", message: "All accessories are updated" });
      }
      const updatedSubSubCategory = await SubSubCatagory.updateOne({ _id: req.params.id }, data[0], { new: true });
      return res.status(200).json({ message: "Success", updatedSubSubCategory });
    } else {
      // Save if the length of the array is not 1
      const newSubSubCategory = new SubSubCatagory(data);
      await newSubSubCategory.save();
      res.status(200).json({ message: "New subsubcatagory saved successfully", newSubSubCategory });
    }
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};






exports.GetAllCatagory = async function (req, res) {
  console.log("abc=1====", req.params.id);
  let searchQuery = req.params.id;
  try {
    const subsubcatagories = await SubSubCatagory.find({ productPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};



exports.GetAllSubSubCatagoryByPermitedType = async function (req, res) {
  console.log("abc=1====", req.params.id);
  let searchQuery = req.params.id;
  try {
    const subsubcatagories = await SubSubCatagory.find({ productPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};


exports.GetAllSubSubCatagoryByPermitedTypeTS = async function (req, res) {
  console.log("abc=1====", req.params.id);
  let searchQuery = req.params.id;
  try {
    const subsubcatagories = await SubSubCatagory.find({ wholesellerPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};





exports.GetByAcc = async function (req, res) {
  console.log("Fetching by subsubcatagory name:", req.params.name);
  let name = req.params.name;

  try {
    // Step 1: Get the main products based on subsubcatagory name
    const subsubcatagories = await SubSubCatagory.find({
      subsubcatagory: { $regex: `^\\s*${name}\\s*$`, $options: "i" },
      productPrice: { $ne: 0, $exists: true }
    });

    // Step 2: Prepare to find related variants
    let variantList = [];

    // Step 3: Loop through fetched items to get their subcategory ID and Name
    for (const item of subsubcatagories) {
      const relatedVariants = await SubSubCatagory.find(
        {
          subcatagory: item.subcatagory,
          subcatagoryid: item.subcatagoryid,
          imageSubsubCatagory: { $exists: true, $ne: null },
          variant: { $exists: true, $ne: null },
          variantName: { $exists: true, $ne: null }
        },
        {
          variant: 1,
          variantName: 1,
          imageSubsubCatagory: 1,
          subcatagory: 1,
          subcatagoryid: 1,
          subsubcatagory: 1,
          _id: 0
        }
      );

      // Push the variants into a common list
      variantList.push(...relatedVariants);
    }

    // Optional: Remove duplicates based on composite key
    const uniqueVariants = Array.from(
      new Map(variantList.map(item => [
        item.variant + item.variantName + item.subcatagoryid + item.subsubcatagory + item.imageSubsubCatagory,
        item
      ])).values()
    );

    // Final response
    res.status(200).json({
      message: "Success",
      subsubcatagories,
      relatedVariants: uniqueVariants
    });

  } catch (error) {
    console.log("GetByAcc error:", error);
    res.status(404).json({ success: false, message: error.message });
  }
};





exports.GetByAccTS = async function (req, res) {
  console.log("abc=1====", req.params.name);
  let name = req.params.name;
  try {
    const subsubcatagories = await SubSubCatagory.find({ subsubcatagory: { $regex: `^\\s*${name}\\s*$`, $options: "i" }, wholesellerPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};



exports.GetModelByModel = async function (req, res) {
  let model = req.params.model;
  try {
    const subsubcatagories = await SubSubCatagory.find({ subcatagory: { $regex: `^\\s*${model}\\s*$`, $options: "i" }, $and: [{ productPrice: { $ne: 0 } }, { productPrice: { $ne: null } }] });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};


exports.GetModelByModelTS = async function (req, res) {
  let model = req.params.model;
  try {
    const subsubcatagories = await SubSubCatagory.find({ subcatagory: { $regex: `^\\s*${model}\\s*$`, $options: "i" }, wholesellerPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};

exports.GetModelByModelbybrandalso = async function (req, res) {
  let model = req.params.model;
  let brand = req.params.brand;
  try {
    const subsubcatagories = await SubSubCatagory.find({
      subcatagory: { $regex: `^\\s*${model}\\s*$`, $options: "i" },
      catagory: { $regex: `^\\s*${catagory}\\s*$`, $options: "i" },
      productPrice: { $ne: 0, $exists: true }
    });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};

exports.GetModelByModelbybrandalsoTS = async function (req, res) {
  let model = req.params.model;
  let brand = req.params.brand;
  try {
    const subsubcatagories = await SubSubCatagory.find({ subcatagory: model, catagory: brand, wholesellerPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};


exports.GetModelByAcc = async function (req, res) {
  console.log("abc=1====", req.params.brand);
  let brand = req.params.brand.trim(); // Remove unnecessary spaces

  try {
    // Use indexes for faster lookups (ensure 'catagory' is indexed in MongoDB)
    const subsubcatagories = await SubSubCatagory.find(
      { 
        catagory: new RegExp(`^${brand}$`, "i"), // More optimized regex
        productPrice: { $gt: 0 } // Use $gt instead of $ne + $exists
      }
    ).select("subcatagory"); // Select only required fields to reduce payload

    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.error("is match 1st error===>>>", error);
    res.status(500).json({ success: false, message: "Internal Server Error" });
  }
};



exports.GetModelByAccTS = async function (req, res) {
  console.log("abc=1====", req.params.name);
  let brand = req.params.brand;
  try {
    const subsubcatagories = await SubSubCatagory.find({ catagory: { $regex: `^\\s*${brand}\\s*$`, $options: "i" }, wholesellerPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};


exports.GetAllAMP = async function (req, res) {
  console.log("abc=1====", req.params.name);
  let name = req.params.name;
  let model = req.params.model;
  try {
    const subsubcatagories = await SubSubCatagory.find({ subsubcatagory: { $regex: `^\\s*${name}\\s*$`, $options: "i" }, subcatagory: { $regex: `^\\s*${model}\\s*$`, $options: "i" }, productPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};

exports.GetAllAMPTS = async function (req, res) {
  console.log("abc=1====", req.params.name);
  let name = req.params.name;
  let model = req.params.model;
  try {
    const subsubcatagories = await SubSubCatagory.find({ subsubcatagory: { $regex: `^\\s*${name}\\s*$`, $options: "i" }, subcatagory: { $regex: `^\\s*${model}\\s*$`, $options: "i" }, wholesellerPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};


exports.getAllBrandModel = async function (req, res) {
  console.log("abc=1====", req.params.model);
  let brand = req.params.brand;
  let model = req.params.model;
  try {
    const subsubcatagories = await SubSubCatagory.find({ catagory: { $regex: `^\\s*${brand}\\s*$`, $options: "i" }, subcatagory: { $regex: `^\\s*${model}\\s*$`, $options: "i" }, productPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};
exports.getAllBrandModelTS = async function (req, res) {
  console.log("abc=1====", req.params.model);
  let brand = req.params.brand;
  let model = req.params.model;
  try {
    const subsubcatagories = await SubSubCatagory.find({ catagory: { $regex: `^\\s*${brand}\\s*$`, $options: "i" }, subcatagory: { $regex: `^\\s*${model}\\s*$`, $options: "i" }, wholesellerPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};




exports.getAllByTypeByBrand = async function (req, res) {
  console.log("abc=1====", req.params.type);
  let type = req.params.type;
  let brand = req.params.brand;
  try {
    const subsubcatagories = await SubSubCatagory.find({ typeName: { $regex: `^\\s*${type}\\s*$`, $options: "i" }, catagory: { $regex: `^\\s*${brand}\\s*$`, $options: "i" }, productPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};

exports.getAllByTypeByBrandTS = async function (req, res) {
  console.log("abc=1====", req.params.type);
  let type = req.params.type;
  let brand = req.params.brand;
  try {
    const subsubcatagories = await SubSubCatagory.find({ typeName: { $regex: `^\\s*${type}\\s*$`, $options: "i" }, catagory: { $regex: `^\\s*${brand}\\s*$`, $options: "i" }, wholesellerPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};
exports.getAllByBrandDD = async function (req, res) {
  let brand = req.params.brand;
  try {
    const subsubcatagories = await SubSubCatagory.find({ catagoryid: brand });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};


exports.getAllByBrand = async function (req, res) {
  let brand = req.params.brand;
  try {
    const subsubcatagories = await SubSubCatagory.find({ catagoryid: brand, productPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};

exports.getAllByModelDD = async function (req, res) {
  let model = req.params.model;
  try {
    const subsubcatagories = await SubSubCatagory.find({ subcatagoryid: model });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};

exports.getAllByModel = async function (req, res) {
  let model = req.params.model;
  try {
    const subsubcatagories = await SubSubCatagory.find({ subcatagoryid: model, productPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};

exports.getAllByType = async function (req, res) {
  let type = req.params.type;
  try {
    const subsubcatagories = await SubSubCatagory.find({ typeName: { $regex: `^\\s*${type}\\s*$`, $options: "i" }, productPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};


exports.getAllByTypeTS = async function (req, res) {
  let type = req.params.type;
  try {
    const subsubcatagories = await SubSubCatagory.find({ typeName: { $regex: `^\\s*${type}\\s*$`, $options: "i" }, wholesellerPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};



exports.getAllByTypeDD = async function (req, res) {
  let type = req.params.type;
  try {
    const subsubcatagories = await SubSubCatagory.find({ typeName: { $regex: `^\\s*${type}\\s*$`, $options: "i" } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};


exports.getAllByTypeByModel = async function (req, res) {
  console.log("abc=1====", req.params.type);
  let type = req.params.type;
  let model = req.params.model;
  try {
    const subsubcatagories = await SubSubCatagory.find({ typeName: { $regex: `^\\s*${type}\\s*$`, $options: "i" }, subcatagory: { $regex: `^\\s*${model}\\s*$`, $options: "i" }, productPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};


exports.getAllByTypeByModelTS = async function (req, res) {
  console.log("abc=1====", req.params.type);
  let type = req.params.type;
  let model = req.params.model;
  try {
    const subsubcatagories = await SubSubCatagory.find({ typeName: { $regex: `^\\s*${type}\\s*$`, $options: "i" }, subcatagory: { $regex: `^\\s*${model}\\s*$`, $options: "i" }, wholesellerPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};






exports.GetAllById = async function (req, res) {
  console.log("abc=1====", req.params.id);
  let ID = req.params.id;
  try {
    const subsubcatagories = await SubSubCatagory.findOne({ _id: ID, productPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};


exports.GetAllByIdTS = async function (req, res) {
  console.log("abc=1====", req.params.id);
  let ID = req.params.id;
  try {
    const subsubcatagories = await SubSubCatagory.findOne({ _id: ID, wholesellerPrice: { $ne: 0, $exists: true } });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};




exports.updateProductSequence = async (req, res) => {
  try {
    const { productId, targetProductId } = req.body;

    // Fetch products
    const [sourceProduct, targetProduct] = await Promise.all([
      SubSubCatagory.findById(productId),
      SubSubCatagory.findById(targetProductId)
    ]);

    if (!sourceProduct || !targetProduct) {
      return res.status(404).json({ success: false, message: 'Product not found' });
    }

    if (sourceProduct === targetProduct) {
      return res.status(423).json({ success: false, message: 'Same Products cannot be replaced' });
    }

    // Swap the data fields of source and target products
    const updatedSourceProduct = await SubSubCatagory.findByIdAndUpdate(productId, {
      wholesellerPrice: targetProduct.wholesellerPrice,
      stocklimit: targetProduct.stocklimit,
      catagoryid: targetProduct.catagoryid,
      catagory: targetProduct.catagory,
      subcatagory: targetProduct.subcatagory,
      subcatagoryid: targetProduct.subcatagoryid,
      subsubcatagory: targetProduct.subsubcatagory,
      imageSubsubCatagory: targetProduct.imageSubsubCatagory,
      variant: targetProduct.variant,
      variantName: targetProduct.variantName,
      manufacturerName: targetProduct.manufacturerName,
      manufacturer: targetProduct.manufacturer,
      typeName: targetProduct.typeName,
      type: targetProduct.type,
      filter: targetProduct.filter,
      color: targetProduct.color,
      Show: targetProduct.Show,
      details: targetProduct.details,
      specifications: targetProduct.specifications,
      warranty: targetProduct.warranty,
      reviews: targetProduct.reviews,
      combine: targetProduct.combine,
      productPrice: targetProduct.productPrice,
      SKU: targetProduct.SKU,
      qty: targetProduct.qty,
      extra: targetProduct.extra
    }, { new: true });

    const updatedTargetProduct = await SubSubCatagory.findByIdAndUpdate(targetProductId, {
      wholesellerPrice: sourceProduct.wholesellerPrice,
      stocklimit: sourceProduct.stocklimit,
      catagoryid: sourceProduct.catagoryid,
      catagory: sourceProduct.catagory,
      subcatagory: sourceProduct.subcatagory,
      subcatagoryid: sourceProduct.subcatagoryid,
      subsubcatagory: sourceProduct.subsubcatagory,
      imageSubsubCatagory: sourceProduct.imageSubsubCatagory,
      variant: sourceProduct.variant,
      variantName: sourceProduct.variantName,
      manufacturerName: sourceProduct.manufacturerName,
      manufacturer: sourceProduct.manufacturer,
      typeName: sourceProduct.typeName,
      type: sourceProduct.type,
      filter: sourceProduct.filter,
      color: sourceProduct.color,
      Show: sourceProduct.Show,
      details: sourceProduct.details,
      specifications: sourceProduct.specifications,
      warranty: sourceProduct.warranty,
      reviews: sourceProduct.reviews,
      combine: sourceProduct.combine,
      productPrice: sourceProduct.productPrice,
      SKU: sourceProduct.SKU,
      qty: sourceProduct.qty,
      extra: sourceProduct.extra
    }, { new: true });

    res.status(200).json({ success: true, message: 'Product sequence updated successfully' });
  } catch (error) {
    console.error('Error updating product sequence:', error);
    res.status(500).json({ success: false, message: 'Internal server error' });
  }
};



exports.GetSingle = async function (req, res) {
  console.log("abc=11====", req.params.id);
  let searchQuery = req.params.id;
  try {
    const subsubcatagories = await SubSubCatagory.find({
      item: { $regex: new RegExp(searchQuery, "i") },
    });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};


exports.GetByFilterForRetailByType = async function (req, res) {
  console.log("abc=11====", req.query);
  const { manufacturerName, color, variantName, min, max, typeName } = req.query;
  const availableQueries = [];

  try {
    if (manufacturerName) {
      if (Array.isArray(manufacturerName)) {
        const manufQueries = manufacturerName.map(manuf => ({ manufacturerName: { $regex: `^\\s*${manuf}\\s*$`, $options: "i" } }));
        availableQueries.push({ $or: manufQueries });
      } else {
        availableQueries.push({ manufacturerName: { $regex: `^\\s*${manufacturerName}\\s*$`, $options: "i" } });
      }
    }
    if (color) {
      if (Array.isArray(color)) {
        const colorQueries = color.map(colorName => ({ color: { $elemMatch: { name: colorName } } }));
        availableQueries.push({ $or: colorQueries });
      } else {
        availableQueries.push({ color: { $elemMatch: { name: color } } });
      }
    }
    if (variantName) {
      if (Array.isArray(variantName)) {
        const variantQueries = variantName.map((variant) => ({ variantName: { $regex: `^\\s*${variant}\\s*$`, $options: "i" } }));
        availableQueries.push({ $or: variantQueries });
      } else {
        availableQueries.push({ variantName: { $regex: `^\\s*${variantName}\\s*$`, $options: "i" } });
      }
    }

    let data;
    if (availableQueries.length > 0) {
      data = await SubSubCatagory.find({ $and: [{ typeName }, { $or: availableQueries }, { productPrice: { $ne: 0, $exists: true } }] });
    } else {
      data = await SubSubCatagory.find({ typeName, productPrice: { $ne: 0, $exists: true } });
    }

    console.log("data before price filtering=====", data);

    // Filter the data based on min and max price
    if (min || max) {
      const minPrice = min ? parseFloat(min) : Number.MIN_VALUE;
      const maxPrice = max ? parseFloat(max) : Number.MAX_VALUE;

      data = data.filter(item => item.productPrice >= minPrice && item.productPrice <= maxPrice);
    }

    console.log("data after price filtering=====", data);
    res.status(200).json({ message: "Success", data });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};
exports.GetByFilterForRetailByModel = async function (req, res) {
  console.log("abc=11====", req.query);
  const { manufacturerName, color, variantName, min, max, subcatagory } = req.query;
  const availableQueries = [];

  try {
    if (manufacturerName) {
      if (Array.isArray(manufacturerName)) {
        const manufQueries = manufacturerName.map(manuf => ({ manufacturerName: { $regex: `^\\s*${manuf}\\s*$`, $options: "i" } }));
        availableQueries.push({ $or: manufQueries });
      } else {
        availableQueries.push({ manufacturerName: { $regex: `^\\s*${manufacturerName}\\s*$`, $options: "i" } });
      }
    }
    if (color) {
      if (Array.isArray(color)) {
        const colorQueries = color.map(colorName => ({ color: { $elemMatch: { name: colorName } } }));
        availableQueries.push({ $or: colorQueries });
      } else {
        availableQueries.push({ color: { $elemMatch: { name: color } } });
      }
    }
    if (variantName) {
      if (Array.isArray(variantName)) {
        const variantQueries = variantName.map((variant) => ({ variantName: variant }));
        availableQueries.push({ $or: variantQueries });
      } else {
        availableQueries.push({ variantName });
      }
    }

    let data;
    if (availableQueries.length > 0) {
      data = await SubSubCatagory.find({ $and: [{ subcatagory }, { $or: availableQueries }, { productPrice: { $ne: 0, $exists: true } }] });
    } else {
      data = await SubSubCatagory.find({ subcatagory, productPrice: { $ne: 0, $exists: true } });
    }

    console.log("data before price filtering=====", data);

    // Filter the data based on min and max price
    if (min || max) {
      const minPrice = min ? parseFloat(min) : Number.MIN_VALUE;
      const maxPrice = max ? parseFloat(max) : Number.MAX_VALUE;

      data = data.filter(item => item.productPrice >= minPrice && item.productPrice <= maxPrice);
    }

    console.log("data after price filtering=====", data);
    res.status(200).json({ message: "Success", data });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};

exports.GetByFilterForRetailByTypeAndBrand = async function (req, res) {
  console.log("abc=11====", req.query);
  const { manufacturerName, color, variantName, min, max, typeName, catagory } = req.query;
  const availableQueries = [];

  try {
    if (manufacturerName) {
      if (Array.isArray(manufacturerName)) {
        const manufQueries = manufacturerName.map(manuf => ({ manufacturerName: { $regex: `^\\s*${manuf}\\s*$`, $options: "i" } }));
        availableQueries.push({ $or: manufQueries });
      } else {
        availableQueries.push({ manufacturerName: { $regex: `^\\s*${manufacturerName}\\s*$`, $options: "i" } });
      }
    }
    if (color) {
      if (Array.isArray(color)) {
        const colorQueries = color.map(colorName => ({ color: { $elemMatch: { name: colorName } } }));
        availableQueries.push({ $or: colorQueries });
      } else {
        availableQueries.push({ color: { $elemMatch: { name: color } } });
      }
    }
    if (variantName) {
      if (Array.isArray(variantName)) {
        const variantQueries = variantName.map((variant) => ({ variantName: { $regex: `^\\s*${variant}\\s*$`, $options: "i" } }));
        availableQueries.push({ $or: variantQueries });
      } else {
        availableQueries.push({ variantName: { $regex: `^\\s*${variantName}\\s*$`, $options: "i" } });
      }
    }

    let data;
    if (availableQueries.length > 0) {
      data = await SubSubCatagory.find({ $and: [{ $or: availableQueries }, { typeName }, { catagory }, { productPrice: { $ne: 0, $exists: true } }] });
    } else {
      data = await SubSubCatagory.find({ $and: [{ typeName }, { catagory }, { productPrice: { $ne: 0, $exists: true } }] });
    }

    console.log("data before price filtering=====", data);

    // Filter the data based on min and max price
    if (min || max) {
      const minPrice = min ? parseFloat(min) : Number.MIN_VALUE;
      const maxPrice = max ? parseFloat(max) : Number.MAX_VALUE;

      data = data.filter(item => item.productPrice >= minPrice && item.productPrice <= maxPrice);
    }

    console.log("data after price filtering=====", data);
    res.status(200).json({ message: "Success", data });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};

exports.GetByFilterForRetail = async function (req, res) {
  console.log("abc=11====", req.query);
  const { manufacturerName, color, variantName, min, max, typeName, catagory, subcatagory } = req.query;
  const availableQueries = [];

  try {
    if (manufacturerName) {
      if (Array.isArray(manufacturerName)) {
        const manufQueries = manufacturerName.map(manuf => ({ manufacturerName: { $regex: `^\\s*${manuf}\\s*$`, $options: "i" } }));
        availableQueries.push({ $or: manufQueries });
      } else {
        availableQueries.push({ manufacturerName: { $regex: `^\\s*${manufacturerName}\\s*$`, $options: "i" } });
      }
    }
    if (color) {
      if (Array.isArray(color)) {
        const colorQueries = color.map(colorName => ({ color: { $elemMatch: { name: colorName } } }));
        availableQueries.push({ $or: colorQueries });
      } else {
        availableQueries.push({ color: { $elemMatch: { name: color } } });
      }
    }
    if (variantName) {
      if (Array.isArray(variantName)) {
        const variantQueries = variantName.map((variant) => ({ variantName: { $regex: `^\\s*${variant}\\s*$`, $options: "i" } }));
        availableQueries.push({ $or: variantQueries });
      } else {
        availableQueries.push({ variantName: { $regex: `^\\s*${variantName}\\s*$`, $options: "i" } });
      }
    }
    if (typeName) availableQueries.push({ typeName: { $regex: `^\\s*${typeName}\\s*$`, $options: "i" } });
    if (catagory) availableQueries.push({ catagory: { $regex: `^\\s*${catagory}\\s*$`, $options: "i" } });
    if (subcatagory) availableQueries.push({ subcatagory: { $regex: `^\\s*${subcatagory}\\s*$`, $options: "i" } });

    let data;
    if (availableQueries.length > 0) {
      data = await SubSubCatagory.find({ $or: availableQueries });
    } else {
      data = await SubSubCatagory.find({});
    }

    console.log("data before price filtering=====", data);

    // Filter the data based on min and max price
    if (min || max) {
      const minPrice = min ? parseFloat(min) : Number.MIN_VALUE;
      const maxPrice = max ? parseFloat(max) : Number.MAX_VALUE;

      data = data.filter(item => item.productPrice >= minPrice && item.productPrice <= maxPrice);
    }

    console.log("data after price filtering=====", data);
    res.status(200).json({ message: "Success", data });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};


exports.GetByFilterForTrade = async function (req, res) {
  console.log("abc=11====", req.query);
  const { manufacturerName, color, variantName, min, max, typeName, catagory, subcatagory } = req.query;
  const availableQueries = [];

  try {
    if (manufacturerName) {
      if (Array.isArray(manufacturerName)) {
        const manufQueries = manufacturerName.map(manuf => ({ manufacturerName: { $regex: `^\\s*${manuf}\\s*$`, $options: "i" } }));
        availableQueries.push({ $or: manufQueries });
      } else {
        availableQueries.push({ manufacturerName: { $regex: `^\\s*${manufacturerName}\\s*$`, $options: "i" } });
      }
    }
    if (color) {
      if (Array.isArray(color)) {
        const colorQueries = color.map(colorName => ({ color: { $elemMatch: { name: colorName } } }));
        availableQueries.push({ $or: colorQueries });
      } else {
        availableQueries.push({ color: { $elemMatch: { name: color } } });
      }
    }
    if (variantName) {
      if (Array.isArray(variantName)) {
        const variantQueries = variantName.map((variant) => ({ variantName: { $regex: `^\\s*${variant}\\s*$`, $options: "i" } }));
        availableQueries.push({ $or: variantQueries });
      } else {
        availableQueries.push({ variantName: { $regex: `^\\s*${variantName}\\s*$`, $options: "i" } });
      }
    }
    if (typeName) availableQueries.push({ typeName: { $regex: `^\\s*${typeName}\\s*$`, $options: "i" } });
    if (catagory) availableQueries.push({ catagory: { $regex: `^\\s*${catagory}\\s*$`, $options: "i" } });
    if (subcatagory) availableQueries.push({ subcatagory: { $regex: `^\\s*${subcatagory}\\s*$`, $options: "i" } });

    let data;
    if (availableQueries.length > 0) {
      data = await SubSubCatagory.find({ $or: availableQueries });
    } else {
      data = await SubSubCatagory.find({});
    }

    console.log("data before price filtering=====", data);

    // Filter the data based on min and max price
    if (min || max) {
      const minPrice = min ? parseFloat(min) : Number.MIN_VALUE;
      const maxPrice = max ? parseFloat(max) : Number.MAX_VALUE;

      data = data.filter(item => item.wholesellerPrice >= minPrice && item.wholesellerPrice <= maxPrice);
    }

    console.log("data after price filtering=====", data);
    res.status(200).json({ message: "Success", data });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};

exports.GetByFilterForTradeByType = async function (req, res) {
  console.log("abc=11====", req.query);
  const { manufacturerName, color, variantName, min, max, typeName } = req.query;
  const availableQueries = [];

  try {
    if (manufacturerName) {
      if (Array.isArray(manufacturerName)) {
        const manufQueries = manufacturerName.map(manuf => ({ manufacturerName: { $regex: `^\\s*${manuf}\\s*$`, $options: "i" } }));
        availableQueries.push({ $or: manufQueries });
      } else {
        availableQueries.push({ manufacturerName: { $regex: `^\\s*${manufacturerName}\\s*$`, $options: "i" } });
      }
    }
    if (color) {
      if (Array.isArray(color)) {
        const colorQueries = color.map(colorName => ({ color: { $elemMatch: { name: colorName } } }));
        availableQueries.push({ $or: colorQueries });
      } else {
        availableQueries.push({ color: { $elemMatch: { name: color } } });
      }
    }
    if (variantName) {
      if (Array.isArray(variantName)) {
        const variantQueries = variantName.map((variant) => ({ variantName: { $regex: `^\\s*${variant}\\s*$`, $options: "i" } }));
        availableQueries.push({ $or: variantQueries });
      } else {
        availableQueries.push({ variantName: { $regex: `^\\s*${variantName}\\s*$`, $options: "i" } });
      }
    }

    let data;
    if (availableQueries.length > 0) {
      data = await SubSubCatagory.find({ $and: [{ typeName }, { $or: availableQueries }, { wholesellerPrice: { $ne: 0, $exists: true } }] });
    } else {
      data = await SubSubCatagory.find({ typeName, wholesellerPrice: { $ne: 0, $exists: true } });
    }

    console.log("data before price filtering=====", data);

    // Filter the data based on min and max price
    if (min || max) {
      const minPrice = min ? parseFloat(min) : Number.MIN_VALUE;
      const maxPrice = max ? parseFloat(max) : Number.MAX_VALUE;

      data = data.filter(item => item.wholesellerPrice >= minPrice && item.wholesellerPrice <= maxPrice);
    }

    console.log("data after price filtering=====", data);
    res.status(200).json({ message: "Success", data });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};
exports.GetByFilterForTradeByModel = async function (req, res) {
  console.log("abc=11====", req.query);
  const { manufacturerName, color, variantName, min, max, subcatagory } = req.query;
  const availableQueries = [];

  try {
    if (manufacturerName) {
      if (Array.isArray(manufacturerName)) {
        const manufQueries = manufacturerName.map(manuf => ({ manufacturerName: { $regex: `^\\s*${manuf}\\s*$`, $options: "i" } }));
        availableQueries.push({ $or: manufQueries });
      } else {
        availableQueries.push({ manufacturerName: { $regex: `^\\s*${manufacturerName}\\s*$`, $options: "i" } });
      }
    }
    if (color) {
      if (Array.isArray(color)) {
        const colorQueries = color.map(colorName => ({ color: { $elemMatch: { name: colorName } } }));
        availableQueries.push({ $or: colorQueries });
      } else {
        availableQueries.push({ color: { $elemMatch: { name: color } } });
      }
    }
    // if (variantName) availableQueries.push({ variantName });
    if (variantName) {
      if (Array.isArray(variantName)) {
        const variantQueries = variantName.map((variant) => ({ variantName: variant }));
        availableQueries.push({ $or: variantQueries });
      } else {
        availableQueries.push({ variantName });
      }
    }

    let data;
    if (availableQueries.length > 0) {
      data = await SubSubCatagory.find({ $and: [{ subcatagory }, { $or: availableQueries }, { wholesellerPrice: { $ne: 0, $exists: true } }] });
    } else {
      data = await SubSubCatagory.find({ subcatagory, wholesellerPrice: { $ne: 0, $exists: true } });
    }

    console.log("data before price filtering=====", data);

    // Filter the data based on min and max price
    if (min || max) {
      const minPrice = min ? parseFloat(min) : Number.MIN_VALUE;
      const maxPrice = max ? parseFloat(max) : Number.MAX_VALUE;
      data = data.filter(item => item.wholesellerPrice >= minPrice && item.wholesellerPrice <= maxPrice);
    }

    console.log("data after price filtering=====", data);
    res.status(200).json({ message: "Success", data });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};

exports.GetByFilterForTradeByTypeAndBrand = async function (req, res) {
  console.log("abc=11====", req.query);
  const { manufacturerName, color, variantName, min, max, typeName, catagory } = req.query;
  const availableQueries = [];

  try {
    if (manufacturerName) {
      if (Array.isArray(manufacturerName)) {
        const manufQueries = manufacturerName.map(manuf => ({ manufacturerName: { $regex: `^\\s*${manuf}\\s*$`, $options: "i" } }));
        availableQueries.push({ $or: manufQueries });
      } else {
        availableQueries.push({ manufacturerName: { $regex: `^\\s*${manufacturerName}\\s*$`, $options: "i" } });
      }
    }
    // if (color) availableQueries.push({ color: { $elemMatch: { name: color } } });
    if (color) {
      if (Array.isArray(color)) {
        const colorQueries = color.map(colorName => ({ color: { $elemMatch: { name: colorName } } }));
        availableQueries.push({ $or: colorQueries });
      } else {
        availableQueries.push({ color: { $elemMatch: { name: color } } });
      }
    }
    // if (variantName) availableQueries.push({ variantName });
    if (variantName) {
      if (Array.isArray(variantName)) {
        const variantQueries = variantName.map((variant) => ({ variantName: variant }));
        availableQueries.push({ $or: variantQueries });
      } else {
        availableQueries.push({ variantName });
      }
    }

    let data;
    if (availableQueries.length > 0) {
      data = await SubSubCatagory.find({ $and: [{ typeName }, { catagory }, { $or: availableQueries }, { wholesellerPrice: { $ne: 0, $exists: true } }] });
    } else {
      data = await SubSubCatagory.find({ $and: [{ typeName }, { catagory }, { wholesellerPrice: { $ne: 0, $exists: true } }] });
    }

    console.log("data before price filtering=====", data);

    // Filter the data based on min and max price
    if (min || max) {
      const minPrice = min ? parseFloat(min) : Number.MIN_VALUE;
      const maxPrice = max ? parseFloat(max) : Number.MAX_VALUE;

      data = data.filter(item => item.wholesellerPrice >= minPrice && item.wholesellerPrice <= maxPrice);
    }

    console.log("data after price filtering=====", data);
    res.status(200).json({ message: "Success", data });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};





exports.getDataByID = async function (req, res) {
  let ID = req.params.id;
  try {
    const subsubcatagories = await SubSubCatagory.findOne({ _id: ID });
    res.status(200).json({ message: "Success", subsubcatagories });
  } catch (error) {
    console.log("is match 1st error===>>>", error);
    res.status(404).json({ success: false, message: error.message });
  }
};

exports.DeleteSingl = async function (req, res) {
  let ID = req.params.id;
  try {
    SubSubCatagory.deleteOne({ _id: ID }, (err, response) => {
      if (response === null) {
        res.json({ message: "User Not Found" });
      } else {
        console.log("user found");
        res.status(200).json({ response, message: "SuccessDelete" });
      }
    });
  } catch (error) {
    console.log("is match 1st error===>>>");
    res.status(404).json({ success: false, message: error.message });
  }
};

exports.DeleteSubsubcatagory = async function (req, res) {
  let ID = req.params.id;
  try {
    const access = await SubSubCatagory.findOne({ _id: ID });
    if (access.SKU !== '0' && access.SKU !== 0) {
      await SubSubCatagory.deleteMany({ SKU: access.SKU });
    } else {
      SubSubCatagory.deleteOne({ _id: ID }, (err, response) => {
        if (response === null) {
          res.json({ message: "User Not Found" });
        } else {
          console.log("user found");
          res.status(200).json({ response, message: "SuccessDelete" });
        }
      });
    }

  } catch (error) {
    console.log("is match 1st error===>>>");
    res.status(404).json({ success: false, message: error.message });
  }
};


exports.DeleteSubsubcatagoryMany = async function (req, res) {
  console.log("abc-=====", req.body);
  try {
    const idsToDelete = req.body.ids;
    for (const id of idsToDelete) {
      const prod = await SubSubCatagory.findOne({ _id: id });
      if (prod.SKU !== '0') {
        // Delete All Products with this SKU;
        await SubSubCatagory.deleteMany({ SKU: prod.SKU });
      }
      await SubSubCatagory.findByIdAndDelete(id);
    }
    res.status(200).json({ success: true, message: "SuccessDelete" });
  } catch (error) {
    console.log("Error:", error);
    res.status(500).json({ success: false, message: "Internal server error" });
  }
};




exports.DeleteImagebyIndex = async function (req, res) {
  console.log("abc-=====");
  console.log("abc-=====", req.params.id);
  console.log("abc-=====", req.params.index);
  let id = req.params.id;
  let index = req.params.index;
  try {
    const subSubCategory = await SubSubCatagory.findById(id);
    if (!subSubCategory) {
      return res.status(404).json({ success: false, message: "SubSubCategory not found" });
    }
    if (subSubCategory.SKU !== "0" && subSubCategory.SKU !== "") {
      const allAccessories = await SubSubCatagory.find({ SKU: subSubCategory.SKU });
      const updatePromises = allAccessories.map(acessory => {
        acessory.imageSubsubCatagory.splice(index, 1);
        return acessory.save();
      });

      await Promise.all(updatePromises);
    } else {
      subSubCategory.imageSubsubCatagory.splice(index, 1);
      await subSubCategory.save();
      res.status(200).json({ success: true, message: "SuccessDelete" });
    }
  } catch (error) {
    console.log("Error:", error);
    res.status(500).json({ success: false, message: "Internal server error" });
  }
};


exports.getLandingSixRetail = async (req, res) => {
  try {
    // Step 1: Get distinct subcategories
    const subcategories = await SubSubCatagory.distinct("subcatagory", {
      productPrice: { $ne: 0, $exists: true },
    });

    let result = [];
    let round = 0;

    while (result.length < 12 && round < 10) {
      for (let subcat of subcategories) {
        if (result.length >= 12) break;

        const doc = await SubSubCatagory.findOne({
          subcatagory: subcat,
          productPrice: { $ne: 0, $exists: true },
          _id: { $nin: result.map((d) => d._id) }, // avoid duplicates
        }).sort({ createdAt: -1 }); // or use random if you want

        if (doc) result.push(doc);
      }

      round++;
    }

    return res.status(200).json({ success: true, subsubcatagories: result });
  } catch (error) {
    console.error("Error:", error);
    return res.status(500).json({ message: "Unknown Error Occurred at Server" });
  }
};




exports.getLandingSixRetailByType = async (req, res) => {
  try {
    // Step 1: Fetch distinct subcategories with valid product prices
    const subcategories = await SubSubCatagory.aggregate([
      { $match: { productPrice: { $ne: 0, $exists: true } } },
      { $group: { _id: "$subcatagory" } },
      { $project: { subcatagory: "$_id", _id: 0 } }
    ]);

    if (!subcategories.length) {
      return res.status(200).json({ success: true, subsubcatagories: [] });
    }

    // Step 2: Fetch up to 12 latest documents in a single query
    const result = await SubSubCatagory.aggregate([
      {
        $match: {
          subcatagory: { $in: subcategories.map(s => s.subcatagory) },
          typeName: "Offers",
          productPrice: { $ne: 0, $exists: true }
        }
      },
      { $sort: { createdAt: -1 } },
      { $sample: { size: 12 } } // Randomize and limit results efficiently
    ]);

    return res.status(200).json({
      success: true,
      subsubcatagories: result
    });
  } catch (error) {
    console.error("Error fetching landing offers:", error);
    return res.status(500).json({
      message: "Internal Server Error - Unable to fetch offers"
    });
  }
};


exports.getLandingSixTrade = async (req, res) => {
  try {
    const subsubcatagories = await SubSubCatagory.find({ wholesellerPrice: { $ne: 0, $exists: true } }).limit(6);
    return res.status(200).json({ success: true, subsubcatagories });
  } catch (error) {
    return res.status(500).json({ message: 'Unknown Error Occured at Server' });
  }
}

















// ----------------------------New Apis for New Add Accessory Page-------------------------------


exports.getAllSubSubCatagoryByMD = async (req, res) => {
  try {
    const page = parseInt(req.params.page) || 1; // Default Page
    const limit = parseInt(req.params.limit) || 40; // Default Number
    const skip = (page - 1) * limit;

    const aggregationArray = [
      { $sort: { createdAt: -1 } },
      {
        $facet: {
          skuZero: [
            { $match: { SKU: "0" } },
            {
              $project: {
                _id: 1,
                SKU: 1,
                wholesellerPrice: 1,
                stocklimit: 1,
                catagoryid: 1,
                catagory: 1,
                subcatagory: 1,
                subcatagoryid: 1,
                subsubcatagory: 1,
                imageSubsubCatagory: 1,
                variant: 1,
                variantName: 1,
                manufacturerName: 1,
                manufacturer: 1,
                typeName: 1,
                type: 1,
                filter: 1,
                color: 1,
                Show: 1,
                details: 1,
                specifications: 1,
                warranty: 1,
                reviews: 1,
                combine: 1,
                productPrice: 1,
                qty: 1,
                extra: 1,
                createdAt: 1,
                updatedAt: 1
              }
            }
          ],
          otherSkus: [
            { $match: { SKU: { $ne: "0" } } },
            {
              $group: {
                _id: "$SKU",
                subsubcategories: {
                  $push: {
                    _id: "$_id",
                    SKU: "$SKU",
                    wholesellerPrice: "$wholesellerPrice",
                    stocklimit: "$stocklimit",
                    catagoryid: "$catagoryid",
                    catagory: "$catagory",
                    subcatagory: "$subcatagory",
                    subcatagoryid: "$subcatagoryid",
                    subsubcatagory: "$subsubcatagory",
                    imageSubsubCatagory: "$imageSubsubCatagory",
                    variant: "$variant",
                    variantName: "$variantName",
                    manufacturerName: "$manufacturerName",
                    manufacturer: "$manufacturer",
                    typeName: "$typeName",
                    type: "$type",
                    filter: "$filter",
                    color: "$color",
                    Show: "$Show",
                    details: "$details",
                    specifications: "$specifications",
                    warranty: "$warranty",
                    reviews: "$reviews",
                    combine: "$combine",
                    productPrice: "$productPrice",
                    qty: "$qty",
                    extra: "$extra",
                    createdAt: "$createdAt",
                    updatedAt: "$updatedAt"
                  }
                }
              }
            },
            {
              $project: {
                _id: 0,
                SKU: "$_id",
                subsubcategories: 1,
                mergedSubsubCategory: {
                  $mergeObjects: [
                    { $arrayElemAt: ["$subsubcategories", 0] },
                    { models: "$subsubcategories.subcatagory" },
                    { variantsArray: "$subsubcategories.variantName" },
                    { manufacturerArray: "$subsubcategories.manufacturerName" }
                  ]
                }
              }
            }
          ]
        }
      },
      {
        $project: {
          result: {
            $concatArrays: ["$skuZero", "$otherSkus.mergedSubsubCategory"]
          }
        }
      },
      { $unwind: "$result" },
      { $replaceRoot: { newRoot: "$result" } },
      { $sort: { createdAt: -1 } }, // Sort again if necessary after transformations
      { $skip: skip },
      { $limit: limit }
    ];

    // Get the total count of documents
    const countAggregationArray = [
      { $sort: { createdAt: -1 } },
      {
        $facet: {
          skuZero: [
            { $match: { SKU: "0" } },
            {
              $project: {
                _id: 1,
                SKU: 1,
                wholesellerPrice: 1,
                stocklimit: 1,
                catagoryid: 1,
                catagory: 1,
                subcatagory: 1,
                subcatagoryid: 1,
                subsubcatagory: 1,
                imageSubsubCatagory: 1,
                variant: 1,
                variantName: 1,
                manufacturerName: 1,
                manufacturer: 1,
                typeName: 1,
                type: 1,
                filter: 1,
                color: 1,
                Show: 1,
                details: 1,
                specifications: 1,
                warranty: 1,
                reviews: 1,
                combine: 1,
                productPrice: 1,
                qty: 1,
                extra: 1,
                createdAt: 1,
                updatedAt: 1
              }
            }
          ],
          otherSkus: [
            { $match: { SKU: { $ne: "0" } } },
            {
              $group: {
                _id: "$SKU",
                subsubcategories: {
                  $push: {
                    _id: "$_id",
                    SKU: "$SKU",
                    wholesellerPrice: "$wholesellerPrice",
                    stocklimit: "$stocklimit",
                    catagoryid: "$catagoryid",
                    catagory: "$catagory",
                    subcatagory: "$subcatagory",
                    subcatagoryid: "$subcatagoryid",
                    subsubcatagory: "$subsubcatagory",
                    imageSubsubCatagory: "$imageSubsubCatagory",
                    variant: "$variant",
                    variantName: "$variantName",
                    manufacturerName: "$manufacturerName",
                    manufacturer: "$manufacturer",
                    typeName: "$typeName",
                    type: "$type",
                    filter: "$filter",
                    color: "$color",
                    Show: "$Show",
                    details: "$details",
                    specifications: "$specifications",
                    warranty: "$warranty",
                    reviews: "$reviews",
                    combine: "$combine",
                    productPrice: "$productPrice",
                    qty: "$qty",
                    extra: "$extra",
                    createdAt: "$createdAt",
                    updatedAt: "$updatedAt"
                  }
                }
              }
            },
            {
              $project: {
                _id: 0,
                SKU: "$_id",
                subsubcategories: 1,
                mergedSubsubCategory: {
                  $mergeObjects: [
                    { $arrayElemAt: ["$subsubcategories", 0] },
                    { models: "$subsubcategories.subcatagory" },
                    { variantsArray: "$subsubcategories.variantName" },
                    { manufacturerArray: "$subsubcategories.manufacturerName" }
                  ]
                }
              }
            }
          ]
        }
      },
      {
        $project: {
          result: {
            $concatArrays: ["$skuZero", "$otherSkus.mergedSubsubCategory"]
          }
        }
      },
      { $unwind: "$result" },
      { $replaceRoot: { newRoot: "$result" } }
    ];
    const totalCounting = await SubSubCatagory.aggregate(countAggregationArray);
    const totalCount = totalCounting.length;

    const subsubcatagories = await SubSubCatagory.aggregate(aggregationArray);
    res.status(200).json({
      success: true,
      message: "Success",
      limit,
      page,
      totalPages: Math.ceil(totalCount / limit),
      totalCount,
      subsubcatagories,
    });
  } catch (error) {
    console.log('Error getting the accessories', error);
    return res.status(500).json({ success: false, message: 'Unable to get all Accessories', error: error.message });
  }
};




// GET : /api/subsubcatagory/getSSCatsWithBrand/:catagory
exports.getSSCatsWithBrand = async (req, res) => {
  const catagory = req.params.catagory;
  try {
    if (!catagory) {
      return res.status(404).json({ success: false, message: 'Please provide a brand in params' });
    }
    console.log('Here is brand==>>', catagory);

    const aggregationArray = [
      { $match: { catagory } },
      {
        $facet: {
          skuZero: [
            { $match: { SKU: "0" } },
            {
              $project: {
                _id: 1,
                SKU: 1,
                wholesellerPrice: 1,
                stocklimit: 1,
                catagoryid: 1,
                catagory: 1,
                subcatagory: 1,
                subcatagoryid: 1,
                subsubcatagory: 1,
                imageSubsubCatagory: 1,
                variant: 1,
                variantName: 1,
                manufacturerName: 1,
                manufacturer: 1,
                typeName: 1,
                type: 1,
                filter: 1,
                color: 1,
                Show: 1,
                details: 1,
                specifications: 1,
                warranty: 1,
                reviews: 1,
                combine: 1,
                productPrice: 1,
                qty: 1,
                extra: 1,
                createdAt: 1,
                updatedAt: 1
              }
            }
          ],
          otherSkus: [
            { $match: { SKU: { $ne: "0" } } },
            {
              $group: {
                _id: "$SKU",
                subsubcategories: {
                  $push: {
                    _id: "$_id",
                    SKU: "$SKU",
                    wholesellerPrice: "$wholesellerPrice",
                    stocklimit: "$stocklimit",
                    catagoryid: "$catagoryid",
                    catagory: "$catagory",
                    subcatagory: "$subcatagory",
                    subcatagoryid: "$subcatagoryid",
                    subsubcatagory: "$subsubcatagory",
                    imageSubsubCatagory: "$imageSubsubCatagory",
                    variant: "$variant",
                    variantName: "$variantName",
                    manufacturerName: "$manufacturerName",
                    manufacturer: "$manufacturer",
                    typeName: "$typeName",
                    type: "$type",
                    filter: "$filter",
                    color: "$color",
                    Show: "$Show",
                    details: "$details",
                    specifications: "$specifications",
                    warranty: "$warranty",
                    reviews: "$reviews",
                    combine: "$combine",
                    productPrice: "$productPrice",
                    qty: "$qty",
                    extra: "$extra",
                    createdAt: "$createdAt",
                    updatedAt: "$updatedAt"
                  }
                }
              }
            },
            {
              $project: {
                _id: 0,
                SKU: "$_id",
                subsubcategories: 1,
                mergedSubsubCategory: {
                  $mergeObjects: [
                    { $arrayElemAt: ["$subsubcategories", 0] },
                    { models: "$subsubcategories.subcatagory" },
                    { variantsArray: "$subsubcategories.variantName" },
                    { manufacturerArray: "$subsubcategories.manufacturerName" }
                  ]
                }
              }
            }
          ]
        }
      },
      {
        $project: {
          result: {
            $concatArrays: ["$skuZero", "$otherSkus.mergedSubsubCategory"]
          }
        }
      },
      { $unwind: "$result" },
      { $replaceRoot: { newRoot: "$result" } },
      { $sort: { createdAt: -1 } }
    ];

    const subsubcatagories = await SubSubCatagory.aggregate(aggregationArray).exec();
    res.status(200).json({
      success: true,
      message: "Success",
      subsubcatagories: subsubcatagories,
    });
  } catch (error) {
    console.log('Error getting the accessories', error);
    return res.status(500).json({ success: false, message: 'Unable to get all Accessories' });
  }
};


// GET : /api/subsubcatagory/getSSCatsWithModel/:subcatagory
exports.getSSCatsWithModel = async (req, res) => {
  const subcatagory = req.params.subcatagory;
  try {
    if (!subcatagory) {
      return res.status(404).json({ success: false, message: 'Please provide a subcategory in params' });
    }

    const aggregationArray = [
      { $match: { subcatagory: { $regex: `^\\s*${subcatagory}\\s*$`, $options: "i" } } },
      {
        $facet: {
          skuZero: [
            { $match: { SKU: "0" } },
            {
              $project: {
                _id: 1,
                SKU: 1,
                wholesellerPrice: 1,
                stocklimit: 1,
                catagoryid: 1,
                catagory: 1,
                subcatagory: 1,
                subcatagoryid: 1,
                subsubcatagory: 1,
                imageSubsubCatagory: 1,
                variant: 1,
                variantName: 1,
                manufacturerName: 1,
                manufacturer: 1,
                typeName: 1,
                type: 1,
                filter: 1,
                color: 1,
                Show: 1,
                details: 1,
                specifications: 1,
                warranty: 1,
                reviews: 1,
                combine: 1,
                productPrice: 1,
                qty: 1,
                extra: 1,
                createdAt: 1,
                updatedAt: 1
              }
            }
          ],
          otherSkus: [
            { $match: { SKU: { $ne: "0" } } },
            {
              $group: {
                _id: "$SKU",
                subsubcategories: {
                  $push: {
                    _id: "$_id",
                    SKU: "$SKU",
                    wholesellerPrice: "$wholesellerPrice",
                    stocklimit: "$stocklimit",
                    catagoryid: "$catagoryid",
                    catagory: "$catagory",
                    subcatagory: "$subcatagory",
                    subcatagoryid: "$subcatagoryid",
                    subsubcatagory: "$subsubcatagory",
                    imageSubsubCatagory: "$imageSubsubCatagory",
                    variant: "$variant",
                    variantName: "$variantName",
                    manufacturerName: "$manufacturerName",
                    manufacturer: "$manufacturer",
                    typeName: "$typeName",
                    type: "$type",
                    filter: "$filter",
                    color: "$color",
                    Show: "$Show",
                    details: "$details",
                    specifications: "$specifications",
                    warranty: "$warranty",
                    reviews: "$reviews",
                    combine: "$combine",
                    productPrice: "$productPrice",
                    qty: "$qty",
                    extra: "$extra",
                    createdAt: "$createdAt",
                    updatedAt: "$updatedAt"
                  }
                }
              }
            },
            {
              $project: {
                _id: 0,
                SKU: "$_id",
                subsubcategories: 1,
                mergedSubsubCategory: {
                  $mergeObjects: [
                    { $arrayElemAt: ["$subsubcategories", 0] },
                    { models: "$subsubcategories.subcatagory" },
                    { variantsArray: "$subsubcategories.variantName" },
                    { manufacturerArray: "$subsubcategories.manufacturerName" }
                  ]
                }
              }
            }
          ]
        }
      },
      {
        $project: {
          result: {
            $concatArrays: ["$skuZero", "$otherSkus.mergedSubsubCategory"]
          }
        }
      },
      { $unwind: "$result" },
      { $replaceRoot: { newRoot: "$result" } },
      { $sort: { createdAt: -1 } }
    ];

    const subsubcatagories = await SubSubCatagory.aggregate(aggregationArray).exec();
    res.status(200).json({
      success: true,
      message: "Success",
      subsubcatagories: subsubcatagories,
    });
  } catch (error) {
    console.log('Error getting the accessories', error);
    return res.status(500).json({ success: false, message: 'Unable to get all Accessories' });
  }
};


// GET : /api/subsubcatagory/getSSCatsWithType/:type
exports.getSSCatsWithType = async (req, res) => {
  const type = req.params.type;
  try {
    if (!type) {
      return res.status(404).json({ success: false, message: 'Please provide a type in params' });
    }
    const aggregationArray = [
      { $match: { typeName: { $regex: `^\\s*${type}\\s*$`, $options: "i" } } },
      {
        $facet: {
          skuZero: [
            { $match: { SKU: "0" } },
            {
              $project: {
                _id: 1,
                SKU: 1,
                wholesellerPrice: 1,
                stocklimit: 1,
                catagoryid: 1,
                catagory: 1,
                subcatagory: 1,
                subcatagoryid: 1,
                subsubcatagory: 1,
                imageSubsubCatagory: 1,
                variant: 1,
                variantName: 1,
                manufacturerName: 1,
                manufacturer: 1,
                typeName: 1,
                type: 1,
                filter: 1,
                color: 1,
                Show: 1,
                details: 1,
                specifications: 1,
                warranty: 1,
                reviews: 1,
                combine: 1,
                productPrice: 1,
                qty: 1,
                extra: 1,
                createdAt: 1,
                updatedAt: 1
              }
            }
          ],
          otherSkus: [
            { $match: { SKU: { $ne: "0" } } },
            {
              $group: {
                _id: "$SKU",
                subsubcategories: {
                  $push: {
                    _id: "$_id",
                    SKU: "$SKU",
                    wholesellerPrice: "$wholesellerPrice",
                    stocklimit: "$stocklimit",
                    catagoryid: "$catagoryid",
                    catagory: "$catagory",
                    subcatagory: "$subcatagory",
                    subcatagoryid: "$subcatagoryid",
                    subsubcatagory: "$subsubcatagory",
                    imageSubsubCatagory: "$imageSubsubCatagory",
                    variant: "$variant",
                    variantName: "$variantName",
                    manufacturerName: "$manufacturerName",
                    manufacturer: "$manufacturer",
                    typeName: "$typeName",
                    type: "$type",
                    filter: "$filter",
                    color: "$color",
                    Show: "$Show",
                    details: "$details",
                    specifications: "$specifications",
                    warranty: "$warranty",
                    reviews: "$reviews",
                    combine: "$combine",
                    productPrice: "$productPrice",
                    qty: "$qty",
                    extra: "$extra",
                    createdAt: "$createdAt",
                    updatedAt: "$updatedAt"
                  }
                }
              }
            },
            {
              $project: {
                _id: 0,
                SKU: "$_id",
                subsubcategories: 1,
                mergedSubsubCategory: {
                  $mergeObjects: [
                    { $arrayElemAt: ["$subsubcategories", 0] },
                    { models: "$subsubcategories.subcatagory" },
                    { variantsArray: "$subsubcategories.variantName" },
                    { manufacturerArray: "$subsubcategories.manufacturerName" }
                  ]
                }
              }
            }
          ]
        }
      },
      {
        $project: {
          result: {
            $concatArrays: ["$skuZero", "$otherSkus.mergedSubsubCategory"]
          }
        }
      },
      { $unwind: "$result" },
      { $replaceRoot: { newRoot: "$result" } },
      { $sort: { createdAt: -1 } }
    ]

    const subsubcatagories = await SubSubCatagory.aggregate(aggregationArray).sort({ createdAt: -1 });
    res.status(200).json({
      success: true,
      message: "Success",
      subsubcatagories: subsubcatagories,
    });
  } catch (error) {
    console.log('Error geting the accessories', error);
    return res.status(500).json({ success: false, message: 'Unable to get all Accessories' });
  }
}


exports.getProductCountByVariant = async (req, res) => {
  const variant = req.params.variant;
  try {
    if (!variant) {
      return res.status(400).json({ success: false, message: "Kindly Provide the variant in url paramters!" });
    }
    const count = await SubSubCatagory.find({ filter: { $elemMatch: { Variant: { $in: [variant] } } } }).countDocuments();
    return res.status(200).json({ success: true, message: "Successfully found document count!", count });
  } catch (error) {
    console.log('Error finding subsubcatagory count', error);
    return res.status(500).json({ success: false, message: "Error finding subsubcatagory count", error: error.message });
  }
}

exports.getProductCountByManufacturer = async (req, res) => {
  const manufacturer = req.params.manufacturer;
  try {
    if (!manufacturer) {
      return res.status(400).json({ success: false, message: "Kindly Provide the manufacturer in url paramters!" });
    }
    const count = await SubSubCatagory.find({ filter: { $elemMatch: { Manufacturer: { $in: [manufacturer] } } } }).countDocuments();
    return res.status(200).json({ success: true, message: "Successfully found document count!", count });
  } catch (error) {
    console.log('Error finding subsubcatagory count', error);
    return res.status(500).json({ success: false, message: "Error finding subsubcatagory count", error: error.message });
  }
}

exports.getProductCountByColor = async (req, res) => {
  const colorName = req.params.color;
  try {
    if (!colorName) {
      return res.status(400).json({ success: false, message: "Kindly Provide the manufacturer in url paramters!" });
    }
    const count = await SubSubCatagory.countDocuments({
      color: { $elemMatch: { name: colorName } }
    });
    return res.status(200).json({ success: true, message: "Successfully found document count!", count });
  } catch (error) {
    console.log('Error finding subsubcatagory count', error);
    return res.status(500).json({ success: false, message: "Error finding subsubcatagory count", error: error.message });
  }
}


exports.getVariantRemovedFromAll = async (req, res) => {
  const variant = req.params.variant;
  try {
    if (!variant) {
      return res.status(400).json({ success: false, message: "Kindly Provide the variant in url paramters!" });
    }
    await SubSubCatagory.deleteMany(
      { 'filter.Variant': variant }
    );
    return res.status(200).json({ success: true, message: "Successfully Updated all Accessories!" });
  } catch (error) {
    console.log('Error finding subsubcatagory count', error);
    return res.status(500).json({ success: false, message: "Error updating subsubcatagories", error: error.message });
  }
}

exports.getManufacturerRemovedFromAll = async (req, res) => {
  const manufacturer = req.params.manufacturer;
  try {
    if (!manufacturer) {
      return res.status(400).json({ success: false, message: "Kindly Provide the manufacturer in url paramters!" });
    }
    await SubSubCatagory.deleteMany(
      { 'filter.Manufacturer': manufacturer }
    );
    return res.status(200).json({ success: true, message: "Successfully Updated all Accessories!" });
  } catch (error) {
    console.log('Error finding subsubcatagory count', error);
    return res.status(500).json({ success: false, message: "Error updating subsubcatagories", error: error.message });
  }
}

exports.getColorRemovedFromAll = async (req, res) => {
  const colorName = req.params.color;
  try {
    if (!colorName) {
      return res.status(400).json({ success: false, message: "Kindly Provide the color in url paramters!" });
    }
    await SubSubCatagory.updateMany(
      { 'color.name': colorName },
      { $pull: { color: { name: colorName } } }
    );
    return res.status(200).json({ success: true, message: "Successfully Updated all Accessories!" });
  } catch (error) {
    console.log('Error finding subsubcatagory count', error);
    return res.status(500).json({ success: false, message: "Error updating subsubcatagories", error: error.message });
  }
}

// POST: /api/subsubcatagory/createnew

exports.CreateNewAccessory = async (req, res) => {
  try {
    const { accessories } = req.body;
    const newAccessories = await SubSubCatagory.insertMany(accessories);
    return res.status(201).json({
      success: true,
      message: "Accessories created successfully",
      data: newAccessories
    });
  } catch (error) {
    console.log('Error making a new accessory', error);
    return res.status(500).json({ success: false, message: "Error creating a new accessory", error: error.message });
  }
}


exports.getExistingUpdated = async (req, res) => {
  try {
    const { id } = req.params;
    const { data } = req.body;
    if (!id || !data) {
      return res.status(400).json({ success: false, message: 'Must provide accessory id and data' })
    }
    const oldAccess = await SubSubCatagory.findOne({ _id: id });
    if (!oldAccess) {
      return res.status(404).json({ success: false, message: 'Such an accessory was not found!' })
    }
    if (oldAccess.SKU !== "0") {
      // Updating all accessories with this SKU
      await SubSubCatagory.updateMany(
        { SKU: oldAccess.SKU },
        { $set: data }
      );
    } else {
      const updated = await SubSubCatagory.findByIdAndUpdate(oldAccess._id, { $set: data }, { new: true });
    }
    res.status(200).json({ success: true, message: 'Accessory updated successfully' });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message })
  }
}


exports.deleteRequiredAccessories = async (req, res) => {
  try {
    const SKU = req.params.SKU;
    const { variants, models, manufacturers } = req.body;
    console.log(variants, models, manufacturers);
    if (!SKU || SKU === "0") {
      return res.status(400).json({ success: false, message: "Can't Delete Such Accessory with SKU 0" });
    }
    const orQuery = [];
    if (variants.length > 0) {
      orQuery.push({ variantName: { $in: variants } });
    }
    if (models.length > 0) {
      orQuery.push({ subcatagory: { $in: models } });
    }
    if (manufacturers.length > 0) {
      orQuery.push({ manufacturerName: { $in: manufacturers } });
    }
    if (orQuery.length === 0) {
      return res.status(400).json({ success: false, message: 'Please add some data for deleting query!' });
    }
    await SubSubCatagory.deleteMany({
      $and: [
        { SKU },
        { $or: orQuery }
      ]
    });
    return res.status(200).json({ success: true, message: 'Successfully deleted!' });
  } catch (error) {
    return res.status(500).json({ success: false, message: error.message });
  }
}


exports.getASingleAccessory = async (req, res) => {
  const id = req.params.id;
  try {
    if (!id) {
      return res.status(400).json({ success: false, message: "Please provide the id" });
    }
    const access = await SubSubCatagory.findOne({ _id: id });
    if (!access) {
      return res.status(404).json({ success: false, message: "Accessory Not found" });
    }
    if (access.SKU === "0") {
      return res.status(200).json({ success: true, message: "Accessory Found Successfully", subsubcatagory: access });
    }
    const aggregationArray = [
      { $match: { SKU: access.SKU } },
      {
        $group: {
          _id: "$SKU",
          subsubcategories: {
            $push: {
              _id: "$_id",
              SKU: "$SKU",
              wholesellerPrice: "$wholesellerPrice",
              stocklimit: "$stocklimit",
              catagoryid: "$catagoryid",
              catagory: "$catagory",
              subcatagory: "$subcatagory",
              subcatagoryid: "$subcatagoryid",
              subsubcatagory: "$subsubcatagory",
              imageSubsubCatagory: "$imageSubsubCatagory",
              variant: "$variant",
              variantName: "$variantName",
              manufacturerName: "$manufacturerName",
              manufacturer: "$manufacturer",
              typeName: "$typeName",
              type: "$type",
              filter: "$filter",
              color: "$color",
              Show: "$Show",
              details: "$details",
              specifications: "$specifications",
              warranty: "$warranty",
              reviews: "$reviews",
              combine: "$combine",
              productPrice: "$productPrice",
              qty: "$qty",
              extra: "$extra",
              createdAt: "$createdAt",
              updatedAt: "$updatedAt"
            }
          }
        }
      },
      {
        $project: {
          _id: 0,
          SKU: "$_id",
          subsubcategories: 1,
          mergedSubsubCategory: {
            $mergeObjects: [
              { $arrayElemAt: ["$subsubcategories", 0] },
              { models: "$subsubcategories.subcatagory" },
              { variantsArray: "$subsubcategories.variantName" },
              { manufacturerArray: "$subsubcategories.manufacturerName" }
            ]
          }
        }
      }
    ]
    const data = await SubSubCatagory.aggregate(aggregationArray);
    return res.status(200).json({ success: true, message: "Accessory Found Successfully", subsubcatagory: data[0].subsubcategories[0] });
  } catch (error) {
    return res.status(500).json({ success: false, message: error?.message ?? "Error getting accessory" });
  }
}



exports.UpdateManyDataFields = async (req, res) => {
  const { changes } = req.body;
  if (!changes) {
    return res.status(400).json({ success: false, message: 'Please provide changes to update!' });
  }
  try {
    const bulkOps = changes.map(change => ({
      updateOne: {
        filter: { _id: change.id },
        update: { $set: { ...change.data } }
      }
    }));
    await SubSubCatagory.bulkWrite(bulkOps);
    return res.status(200).json({ success: true, message: 'SubCategories Updated Successfully!' });
  } catch (error) {
    return res.status(500).json({ success: false, message: error?.message ?? 'Internal Server Error' });
  }
}





exports.updateSubsubcatagory = async (req, res) => {
  try {
    const filter = {
      typeName: "Nicsalt",
      subcatagory: "Bar Juice 5000",
    };

    const products = await SubSubCatagory.find(filter);

    let updatedCount = 0;

    for (const product of products) {
      const manufacturer = product?.filter?.[0]?.Manufacturer?.[0] || "";
      const variant = product?.filter?.[0]?.Variant?.[0] || "";
      const typeName = product?.typeName || "";

      const subsubcatagory = `${manufacturer} ${variant} ${typeName}`.trim();

      const result = await SubSubCatagory.updateOne(
        { _id: product._id },
        { $set: { subsubcatagory } }
      );

      if (result.modifiedCount > 0) {
        updatedCount++;
      }
    }

    return res.status(200).json({
      message: `Successfully updated ${updatedCount} products.`,
    });
  } catch (error) {
    console.error("Update error:", error);
    return res.status(500).json({
      error: "An error occurred while updating subsubcatagory.",
    });
  }
};