const mongoose = require("mongoose");
const Keyword = mongoose.model("Keyword");
const solr = require('solr-client');
const axios = require("axios");
const { messageBuilder  } = require("../../apps/common/CommonFunctions")
const Maintags =mongoose.model("MainTag")
const ShopperrSubscribeProducts = mongoose.model("ShopperrSubscribeProducts");
const { updateShopperrPriceAlgo } = require("../../apps/middlewares/priceAlgo");
const connectSolr = () => {
  const client = solr.createClient({
    host: process.env.SOLR_DEV_URL,
    port: "8983",
    core: "b2bshopperr",
    path: "/solr",
  });
 // console.log("+++++++++++",client)
  client.ping(function (err, obj) {
    if (err) {
      // console.log(err);
    }
  });
  return client;
};
const AWS = require('aws-sdk');
const ID = '';
const SECRET = '';
// The name of the bucket that you have created
const BUCKET_NAME = 'test-bucket';
const s3 = new AWS.S3({
    accessKeyId: 'AKIAZQ3DPSAOW34EMAWP',
    secretAccessKey: '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'
});


exports.allProduct = async (req, res) => {
  try {
	 let limit = parseInt(req.body.limit) || 10; // Default to 10 if limit is not provided or invalid
	const page = parseInt(req.body.page) || 1;  // Default to page 1 if not provided

	// Ensure limit does not exceed 10
	if (isNaN(limit) || limit > 10) {
		limit = 10;
	}

	// Ensure page is at least 1
	if (isNaN(page) || page < 1) {
		page = 1;
	}

	const startFrom = (page - 1) * limit;
	const client = connectSolr();

	let query = client.query().q("*:*").start(startFrom).rows(limit); // Use `client.query()`, not `createQuery()`

	
	client.search(query, async function (err, obj) {
		if (err) {
			console.log("Solr Error:", err);
			return messageBuilder(res, 500, { ...req.body }, err.toString(), { error: 1 });
		} else {
			const dataToSend = {
				params: { limit, page },
				data: {
					totalRecords: obj.response.numFound,
					returnedRecords: obj.response.docs.length,
					products: obj.response.docs
				},
			};
			return res.json(dataToSend);
		}
	});
	} catch (err) {
    res.status(500).json({});
  }
};
exports.categoryByProduct = async (req, res) => {
    try {
        let { category, page = 1, limit = 10 } = req.body;
        page = Number(page);
        limit = Number(limit);

        // Validate page and limit
        if (isNaN(page) || page < 1) page = 1;
        if (isNaN(limit) || limit > 10 || limit < 1) limit = 10;

        const startFrom = (page - 1) * limit;
        const client = connectSolr();

        if (category) {
            category = category.trim();
        }

        // 🔥 Use q (query) instead of fq (filter query) for exact matching
        let query = client.query().q(`category:"${category}"`).start(startFrom).rows(limit);

        //console.log("🟢 Final Solr Query:", query.toString());

        //console.time("solr-query");
        client.search(query, async function (err, obj) {
            //console.timeEnd("solr-query");
            if (err) {
                //console.error("🔥 Solr Error:", err);
                return res.status(500).json({ error: "Solr query failed", details: err.toString() });
            } else {
                const dataToSend = {
					params: { limit, page },
					data: {
						totalRecords: obj.response.numFound,
						returnedRecords: obj.response.docs.length,
						products: obj.response.docs
					},
				};
				return res.json(dataToSend);
            }
        });
    } catch (err) {
        res.status(500).json({ error: "Internal Server Error", details: err.toString() });
    }
};


exports.searchBySku = async (req, res) => {
    try {
        let { sku } = req.query;

        if (!sku) {
            return res.status(400).json({ error: "SKU is required" });
        }

        sku = sku.trim();
        const client = connectSolr();

        // 🔥 Exact match for SKU
        let query = client.query().q(`sku:"${sku}"`).rows(1); // SKU should be unique, so fetching 1

        //console.log("🟢 Final Solr Query:", query.toString());

        //console.time("solr-query");
        client.search(query, async function (err, obj) {
            console.timeEnd("solr-query");
            if (err) {
                console.error("🔥 Solr Error:", err);
                return res.status(500).json({ error: "Solr query failed", details: err.toString() });
            } else {
                const dataToSend = {
				params: { sku },
				data: {
					totalRecords: obj.response.numFound,
					returnedRecords: obj.response.docs.length,
					products: obj.response.docs
				},
			};
			return res.json(dataToSend);
            }
        });
    } catch (err) {
        res.status(500).json({ error: "Internal Server Error", details: err.toString() });
    }
};

exports.commonSearch = async (req, res) => {
    try {
        let { field, value, page = 1, limit = 10 } = req.body;

        if (!field || !value) {
            return res.status(400).json({ error: "Both field and value are required" });
        }

        page = Number(page);
        limit = Number(limit);

        // Validate page and limit
        if (isNaN(page) || page < 1) page = 1;
        if (isNaN(limit) || limit > 50 || limit < 1) limit = 10;

        const startFrom = (page - 1) * limit;
        const client = connectSolr();

        value = value.trim();
        /*let query =  "";
		if(field == 'name'){
			query = client.query().q(`${field}:"*${value}*"`).start(startFrom).rows(limit);
		} else {
			query = client.query().q(`${field}:"${value}"`).start(startFrom).rows(limit);
		}*/
        // 🔥 Exact match for the given field
        let query = client.query().start(startFrom).rows(limit);

		if (field === "name") {
			// 🔥 Allow partial match for "name" (LIKE search)
			query = query.q(`${field}:*${value}*`);  
		} else {
			// 🔥 Enforce exact match for other fields
			query = query.q(`${field}:"${value}"`);  
		}
        //console.log("🟢 Final Solr Query:", query.toString());

        //console.time("solr-query");
        client.search(query, async function (err, obj) {
            console.timeEnd("solr-query");
            if (err) {
                console.error("🔥 Solr Error:", err);
                return res.status(500).json({ error: "Solr query failed", details: err.toString() });
            } else {
                return res.json({
                    params: { field, value, page, limit },
                    data: {
                        totalRecords: obj.response.numFound,
                        returnedRecords: obj.response.docs.length,
                        products: obj.response.docs,
                    },
                });
            }
        });
    } catch (err) {
        res.status(500).json({ error: "Internal Server Error", details: err.toString() });
    }
};


exports.updateCategoryByTitle = async (req, res) => {
    try {
        const SOLR_SELECT_URL = "http://3.6.168.207:8983/solr/b2bshopperr/select?q=*:*&fl=id,title&rows=1000";
        const SOLR_UPDATE_URL = "http://3.6.168.207:8983/solr/b2bshopperr/update?commit=true";

        const categoryMapping = {
    // ✅ Jewellery
    "ring": "Jewellery",
    "bracelet": "Jewellery",
    "necklace": "Jewellery",
    "earrings": "Jewellery",
    "pendant": "Jewellery",
    "bangle": "Jewellery",
    "jewellery set": "Jewellery",

    // ✅ Clothing & Accessories
    "saree": "Clothing & Accessories",
    "kurta": "Clothing & Accessories",
    "lehenga": "Clothing & Accessories",
    "tshirt": "Clothing & Accessories",
    "jeans": "Clothing & Accessories",
    "jacket": "Clothing & Accessories",
    "dress": "Clothing & Accessories",
    "skirt": "Clothing & Accessories",
    "hoodie": "Clothing & Accessories",
    "trousers": "Clothing & Accessories",

    // ✅ Electronics
    "smartphone": "Electronics",
    "tablet": "Electronics",
    "television": "Electronics",
    "camera": "Electronics",
    "drone": "Electronics",
    "earbuds": "Electronics",
    "charger": "Electronics",
    "gaming console": "Electronics",
    "headphones": "Electronics",
    "speakers": "Electronics",
    "power bank": "Electronics",
    "projector": "Electronics",
    "fitness tracker": "Electronics",
    "usb cable": "Electronics",

    // ✅ Computers & Accessories
    "laptop": "Computers & Accessories",
    "desktop": "Computers & Accessories",
    "monitor": "Computers & Accessories",
    "keyboard": "Computers & Accessories",
    "mouse": "Computers & Accessories",
    "printer": "Computers & Accessories",
    "external hard drive": "Computers & Accessories",
    "graphic card": "Computers & Accessories",
    "motherboard": "Computers & Accessories",
    "ram": "Computers & Accessories",
    "ssd": "Computers & Accessories",

    // ✅ Home & Kitchen
    "kitchen": "Home & Kitchen",
    "furniture": "Home & Kitchen",
    "bed": "Home & Kitchen",
    "mattress": "Home & Kitchen",
    "dining table": "Home & Kitchen",
    "sofa": "Home & Kitchen",
    "refrigerator": "Home & Kitchen",
    "microwave": "Home & Kitchen",
    "washing machine": "Home & Kitchen",
    "blender": "Home & Kitchen",
    "coffee maker": "Home & Kitchen",
    "air fryer": "Home & Kitchen",
    "dishwasher": "Home & Kitchen",
    "pressure cooker": "Home & Kitchen",

    // ✅ Watches
    "watch": "Watches",
    "smartwatch": "Watches",
    "digital watch": "Watches",
    "analog watch": "Watches",

    // ✅ Books
    "book": "Books",
    "novel": "Books",
    "magazine": "Books",
    "comic": "Books",
    "encyclopedia": "Books",

    // ✅ Toys & Games
    "toy": "Toys & Games",
    "board game": "Toys & Games",
    "puzzle": "Toys & Games",
    "lego": "Toys & Games",
    "remote control car": "Toys & Games",
    "doll": "Toys & Games",
    "stuffed animal": "Toys & Games",
    "action figure": "Toys & Games",
    "building blocks": "Toys & Games",

    // ✅ Beauty & Personal Care
    "lipstick": "Beauty",
    "foundation": "Beauty",
    "moisturizer": "Beauty",
    "face cream": "Beauty",
    "perfume": "Beauty",
    "shampoo": "Beauty",
    "conditioner": "Beauty",
    "nail polish": "Beauty",
    "hair dryer": "Beauty",
    "hair straightener": "Beauty",
    "makeup brush": "Beauty",

    // ✅ Sports, Fitness & Outdoors
    "treadmill": "Sports, Fitness & Outdoors",
    "dumbbell": "Sports, Fitness & Outdoors",
    "yoga mat": "Sports, Fitness & Outdoors",
    "cricket bat": "Sports, Fitness & Outdoors",
    "football": "Sports, Fitness & Outdoors",
    "badminton racket": "Sports, Fitness & Outdoors",
    "cycling helmet": "Sports, Fitness & Outdoors",
    "boxing gloves": "Sports, Fitness & Outdoors",

    // ✅ Baby Products
    "diaper": "Baby",
    "baby bottle": "Baby",
    "stroller": "Baby",
    "crib": "Baby",
    "baby wipes": "Baby",

    // ✅ Pet Supplies
    "dog food": "Pet Supplies",
    "cat litter": "Pet Supplies",
    "fish tank": "Pet Supplies",
    "bird cage": "Pet Supplies",
    "dog leash": "Pet Supplies",
    "pet bed": "Pet Supplies",

    // ✅ Car & Motorbike
    "helmet": "Car & Motorbike",
    "car cover": "Car & Motorbike",
    "motor oil": "Car & Motorbike",
    "seat cover": "Car & Motorbike",
    "tyre inflator": "Car & Motorbike",
    "car vacuum cleaner": "Car & Motorbike",

    // ✅ Musical Instruments
    "guitar": "Musical Instruments",
    "piano": "Musical Instruments",
    "violin": "Musical Instruments",
    "drum": "Musical Instruments",
    "flute": "Musical Instruments",

    // ✅ Software
    "antivirus": "Software",
    "photo editor": "Software",
    "video editor": "Software",
    "operating system": "Software",
    "programming tool": "Software",

    // ✅ Video Games
    "gaming mouse": "Video Games",
    "gaming keyboard": "Video Games",
    "gaming headset": "Video Games",
    "playstation": "Video Games",
    "xbox": "Video Games",
    "nintendo switch": "Video Games",

    // ✅ Office Products
    "printer": "Office Products",
    "scanner": "Office Products",
    "stationery": "Office Products",
    "office chair": "Office Products",
    "desk organizer": "Office Products",

    // ✅ Industrial & Scientific
    "power tools": "Industrial & Scientific",
    "microscope": "Industrial & Scientific",
    "oscilloscope": "Industrial & Scientific",
    "safety goggles": "Industrial & Scientific",

    // ✅ Luggage & Bags
    "suitcase": "Luggage & Bags",
    "backpack": "Luggage & Bags",
    "duffel bag": "Luggage & Bags",
    "handbag": "Luggage & Bags",

    // ✅ Shoes & Handbags
    "sneakers": "Shoes & Handbags",
    "formal shoes": "Shoes & Handbags",
    "heels": "Shoes & Handbags",
    "sandals": "Shoes & Handbags",

    // ✅ Health & Personal Care
    "vitamin": "Health & Personal Care",
    "protein supplement": "Health & Personal Care",
    "blood pressure monitor": "Health & Personal Care",
    "glucometer": "Health & Personal Care",

    // ✅ Party Supplies
    "balloon": "Party Supplies",
    "birthday decoration": "Party Supplies",
    "photo props": "Photography & Accessories",

    // ✅ Appliances
    "air conditioner": "Appliances",
    "water purifier": "Appliances",
    "vacuum cleaner": "Appliances",
    "electric kettle": "Appliances"
};


        // Fetch all documents from Solr
        const response = await axios.get(SOLR_SELECT_URL);
        const docs = response.data.response.docs || [];

        if (docs.length === 0) {
            return res.status(404).json({ message: "No documents found in Solr." });
        }

        const categoryKeys = Object.keys(categoryMapping);

        const updatePayload = docs.map(doc => {
            const title = (doc.title || "").toLowerCase();
            let assignedCategory = "Uncategorized";

            // Tokenize the title into words
            const words = title.split(/\s+/);

            let bestMatch = null;
            let highestScore = 0;

            words.forEach(word => {
                const matches = stringSimilarity.findBestMatch(word, categoryKeys);
                const best = matches.bestMatch;

                if (best.rating > highestScore && best.rating >= 0.5) {
                    bestMatch = best.target;
                    highestScore = best.rating;
                }
            });

            if (bestMatch) {
                assignedCategory = categoryMapping[bestMatch];
            }

            return {
                id: doc.id,
                category: { set: assignedCategory }
            };
        });

        // Send update request to Solr
        const updateResponse = await axios.post(SOLR_UPDATE_URL, updatePayload, {
            headers: { "Content-Type": "application/json" }
        });

        if (updateResponse.status === 200) {
            return res.status(200).json({ message: "Categories updated successfully!" });
        } else {
            console.error("Failed to update categories:", updateResponse.data);
            return res.status(500).json({ error: "Failed to update categories." });
        }
    } catch (err) {
        console.error("Error updating categories:", err.message);
        return res.status(500).json({ error: "Internal Server Error", details: err.message });
    }
};



exports.getSingleProductByHandle = async (req, res) => {
  const connectSolr = () => {
    const client = solr.createClient({
      host: process.env.SOLR_DEV_URL,
      port: '8983',
      core: 'b2bshopperr',
      path: '/solr',
      timeout: 30000, 
    });
    client.ping((err, obj) => {
      if (err) {
    
        return messageBuilder(res, 500, req.body, 'Solr Ping Error', { error: 1 });
      }
    });
    return client;
  };

  const { url } = req.body;  
// console.log(url)
  if (!url) {
    return res.status(400).json({ status: 400, msg: "Invalid Input Param" });
  }

  try {
    const solrClient = connectSolr();

    // Construct the Solr query using the url from the request
    const query = `q=url:${url}&start=0&rows=1`;
  // console.log(query)

  let solrUrl = `http://${process.env.SOLR_DEV_URL}:8983/solr/b2bshopperr/select?defType=dismax&q=${query}`;
  //  console.log(solrUrl);
   try {
    const resp = await axios.get(encodeURI(solrUrl));
    // console.log(resp);
    const dataToSend = {
      data: {
        //totalRecords: resp.data.response.numFound,
        products: formatData(resp.data.response.docs)
      },
    };
    //console.log(JSON.stringify(dataToSend));
    return messageBuilder(res, 200, { ...req.body },"", dataToSend);

    // return res.status(200).json({
    //   numFounds: resp.data.response.numFound,
    //   data: formatData(resp.data.response.docs),
    // });
  } catch (err) {
    res.status(500).json({});
  }
    
  } catch (err) {
    return res.status(500).json({ err });
  }
};



exports.topratedProducts = async (req, res) => {
  const connectSolr = () => {
    const client = solr.createClient({
      host: process.env.SOLR_DEV_URL,
      port: '8983',
      core: 'b2bshopperr',
      path: '/solr',
      timeout: 30000, // Increased timeout for Solr queries
    });

    // Ping Solr to check connection
    client.ping((err, obj) => {
      if (err) {
        // console.error('Solr Ping Error:', err);
        return messageBuilder(res, 500, req.body, 'Solr Ping Error', { error: 1 });
      } else {
        // console.log('Solr Ping Success:', obj);
      }
    });
    return client;
  };
  // console.log(req.body.keyword)
  // const keyword = "children, headset, hair spray, hanger, wireless copy remote, shark, adhesive socket, fixture, blade" //req.body.keyword || "eBay Motors";
  const keyword = req.body.keyword?req.body.keyword:"children, headset, hair spray, hanger, wireless copy remote, shark, adhesive socket, fixture, blade" //req.body.keyword || "eBay Motors";
  
  
  let page = parseInt(1);
  let limit = parseInt(5);
  let pageNumber=1

  let skip = (page - 1) * limit;
  let computedVariable = "";

  if (req.body.title) {
    computedVariable = computedVariable + `&qf=title^4 OR`;
  }

  if (req.body.description) {
    computedVariable = computedVariable + `&qf=description^2 OR`;
  }

  if (req.body.tags) {
    computedVariable = computedVariable + `&qf=tags^1.5 OR`;
  }
  let solrUrl = `http://${process.env.SOLR_DEV_URL}:8983/solr/b2bshopperr/select?defType=dismax&q=${keyword}${computedVariable}&start=${skip}&rows=${limit}`;
  // console.log(solrUrl);
  try {
    const resp = await axios.get(encodeURI(solrUrl));
    // console.log(resp);
    const dataToSend = {
      data: {
        totalRecords: resp.data.response.numFound,
        products: formatData(resp.data.response.docs)
      },
    };
    //console.log(dataToSend);
    return messageBuilder(res, 200, { ...req.body },"", dataToSend);

    // return res.status(200).json({
    //   numFounds: resp.data.response.numFound,
    //   data: formatData(resp.data.response.docs),
    // });
  } catch (err) {
    res.status(500).json({});
  }
};

// exports.topratedProducts = async (req, res) => {
  
  
//   try {
//     const expectedSourceObj = { ios: 1, android: 2, web: 3 };   
//     const expectedSourceArr = Object.keys(expectedSourceObj);
//     const keyword = req.body.keyword || "*";
//     const limit = parseInt(req.body.limit);
//     const pageNumber = parseInt(req.body.pageNumber);
//     const type = parseInt(req.body.type);
//     const source = req.body.source;
//     const arrayType = [1, 2, 3, 4, 5];

//     if (!limit || !pageNumber || !type || !source) {
//       return messageBuilder(res, 400, { ...req.body }, "Invalid Input Param", { error: 1 });
//     }
//     if (!source || !expectedSourceArr.includes(source.toLowerCase())) {
//       return messageBuilder(res, 400, { ...req.body }, "Invalid Input Param : source can not be null and should be one of value [android,ios,web]", { error: 1 });
//     }
//     if (!arrayType.includes(type)) {
//       return messageBuilder(res, 400, { ...req.body }, "type should be in 1,2,3,4,5", { error: 1 });
//     }
//     try {
//       if(keyword){
//         const keywordCreated = new Keyword({
//           name: keyword,
//           source: expectedSourceObj[source.toLowerCase()],
          
//         });
        
//         await keywordCreated.save();
//       }
//     } catch (err) {
//       return messageBuilder(res, 500, { ...req.body }, err.toString(), { error: 1 });
//     }
//     const startFrom = (parseInt(pageNumber) - 1) * parseInt(limit);
//     const client = connectSolr();
//     // console.log(client);
//     let query = client
//     .createQuery();
//     if(keyword){
//       query = query.q(`%${keyword}%`);
//     }
//     query = query.start(startFrom)
//     .rows(limit);
//     // // .matchFilter("color", "*")
//     // //.matchFilter("size", "S")
//     // .facet({ on: true, field: "color" })
//     // .facet({ on: true, field: "size" })
//     // .facet({ on: true, field: "style" });
//     client.search(query, async function (err, obj) {
//       if (err) {
//         console.log(err);
//         throw err;
//       } else {
//         const dataToSend = {
//           params: {
//             keyword,
//             limit,
//             pageNumber,
//             source,
//           },
//           data: {
//             totalRecords: obj.response.numFound,
//             products: await formatData(obj.response.docs,null)
//           },
//         };
//         return messageBuilder(res, 200, { ...req.body },"", dataToSend);
//       }
//     });
//   } catch (err) {
//     return messageBuilder(res, 500, { ...req.body },err.toString(),{error:1});
//   }
// };
const formatData = (obj) => {
  if (obj.length > 0) {
    const formattedData = obj.map(({ imgUrl = [], ...otherValues }) => {
      // console.log(obj)
      const supplier_id = obj[0].author;

      const appendImgUrl = imgUrl.slice(0, 50).map((img) => {
        
        // console.log(supplier_id)
        
        if(supplier_id=='67405479bf97f7739fb486a0'){
          return {
            // src: `${process.env.S3_BUCKET_FILE_URL}/${img}`,
            src: `${img}`,
          };
        }else{
          return {
            src: `${process.env.S3_BUCKET_FILE_URL}/${img}`,
            // src: `${img}`,
          };
        }
       
        
      });
      const {
        title,
        id,
        url,
        description,
        inStock,
        sku,
        price,
        mrp,
        variantOptions = [],
        variantDescription = [],
        tags,
      } = otherValues;
      // let subscribedFlag = false;
      // if (merchantId && mongoose.isValidObjectId(merchantId)) {
      //   const SubscribeProduct = await ShopperrSubscribeProducts.findOne({
      //     mId: mongoose.Types.ObjectId(merchantId),
      //     pId: mongoose.Types.ObjectId(id),
      //   });
      //   if (SubscribeProduct) {
      //     subscribedFlag = true;
      //   }
      // }
      return {
        tags,
        title,
        imgUrl: appendImgUrl,
        _id: id,
        url: url,
        description,
        quantity: inStock,
        sku,
        sellingPrice: price,
        recommendedRetailPrice: parseFloat(new Number(mrp).toFixed(2)),
        variantOptions:
          variantOptions.length > 0 ? prepareVO(variantOptions) : [],
        variantDescription:
          variantDescription.length > 0 ? prepareVD(variantDescription) : [],
        // isSubscribed: merchantId ? subscribedFlag : false,
      };
    });
    return formattedData;
  } else return [];
};
const prepareVO = (variantOptions) => {
  if (variantOptions.length > 0) {
    const variantOptionsObj = variantOptions.map((obj) => {
      const removeBraces = obj.substring(1, obj.length - 1);
      const objkeypair = removeBraces.replace(/=/g, ":").replace(/ /g, "");
      const obje = objkeypair.substring(
        objkeypair.indexOf("name") + 5,
        objkeypair.indexOf("values") - 1
      );
      const value = objkeypair.substring(
        objkeypair.indexOf("values") + 7,
        objkeypair.indexOf("]") + 1
      );
      return {
        name: obje,
        values: value.replace(/[\[\]']+/g, "").split(","),
      };
    });
    return variantOptionsObj;
  } else return [];
};

const prepareVD = (variantDesc) => {
  const variantDescriptionObj = variantDesc.map((item) => {
    const makeobject = item.replace(/(\b\S+\b)=(\b\S+\b)/g, '"$1":"$2"');
    const obj = JSON.parse(makeobject);
    return obj;
  });

  const variantArrayObj = variantDescriptionObj.map(
    ({ price, mrp, sp, quantity, sellingPrice, cogs, ...other }) => {
      return {
        ...other,
        price: parseFloat(new Number(price).toFixed(2)),
        mrp: parseFloat(new Number(mrp).toFixed(2)),
        sp: parseFloat(new Number(sp).toFixed(2)),
        sellingPrice: parseFloat(new Number(sellingPrice).toFixed(2)),
        quantity: parseInt(quantity),
      };
    }
  );

  return variantArrayObj;
};
exports.searchProducts = async (req, res) => {
  const connectSolr = () => {
    const client = solr.createClient({
      host: process.env.SOLR_DEV_URL,
      port: '8983',
      core: 'b2bshopperr',
      path: '/solr',
      timeout: 30000, // Increased timeout for Solr queries
    });

    // Ping Solr to check connection
    client.ping((err, obj) => {
      if (err) {
        // console.error('Solr Ping Error:', err);
        return messageBuilder(res, 500, req.body, 'Solr Ping Error', { error: 1 });
      } else {
        // console.log('Solr Ping Success:', obj);
      }
    });
    return client;
  };
  const keyword = req.body.keyword || "";
  let page = parseInt(1);
  let limit = parseInt(100);
  let pageNumber=1

  let skip = (page - 1) * limit;
  let computedVariable = "";

  if (req.body.title) {
    computedVariable = computedVariable + `&qf=title^4 OR`;
  }

  if (req.body.description) {
    computedVariable = computedVariable + `&qf=description^2 OR`;
  }

  if (req.body.tags) {
    computedVariable = computedVariable + `&qf=tags^1.5 OR`;
  }
  let solrUrl = `http://${process.env.SOLR_DEV_URL}:8983/solr/b2bshopperr/select?defType=dismax&q=${keyword}${computedVariable}&start=${skip}&rows=${limit}`;
  // console.log(solrUrl);
  try {
    const resp = await axios.get(encodeURI(solrUrl));
    // console.log(resp);
    const dataToSend = {
      data: {
        totalRecords: resp.data.response.numFound,
        products: formatData(resp.data.response.docs)
      },
    };
    //console.log(dataToSend);
    return messageBuilder(res, 200, { ...req.body },"", dataToSend);

    // return res.status(200).json({
    //   numFounds: resp.data.response.numFound,
    //   data: formatData(resp.data.response.docs),
    // });
  } catch (err) {
    res.status(500).json({});
  }
};

