import mongoose from "mongoose"; import { GetProductsResult, GetProductsInput } from "./types"; import { Product, Menu } from "../../../models/"; const getProducts = async (userID: string, query: GetProductsInput): Promise => { try { const { categoryIDs, search } = query; const matchStage: any = { userID: new mongoose.Types.ObjectId(userID), isActive: true }; if (categoryIDs) { matchStage.categoryIDs = { $in: categoryIDs.map(id => new mongoose.Types.ObjectId(id)) }; } if (search) { matchStage.$or = [ { title: { $regex: search, $options: "i" } }, { description: { $regex: search, $options: "i" } } ]; } const activeMenu = await Menu.findOne({ userID: new mongoose.Types.ObjectId(userID), isActive: true }); if (!activeMenu) { return { message: "no-products-found-in-active-menu", code: 404 }; } const activeProductIDs = activeMenu.products.map((p) => p.productID); matchStage._id = { $in: activeProductIDs }; const products = await Product.aggregate([ { $match: matchStage }, { $lookup: { from: "categories", localField: "categoryIDs", foreignField: "_id", as: "categoryIDs" } }, { $sort: { createdAt: -1 } } ]); const payload = products.map((product) => ({ ...product, categoryIDs: product.categoryIDs.map((cat: any) => cat._id.toString()) })); return { message: "products-retrieved-successfully", payload: payload, code: 200 }; } catch (error) { console.error("GetProducts action error:", error); return { message: "internal-server-error", code: 500 }; } }; export default getProducts;