import { Product } from "../models/Product.js";

export async function listProducts(request, response) {
  const { category, q, min, max } = request.query;
  const query = {};
  if (category) query.category = category;
  if (q) query.$text = { $search: q };
  if (min || max) query.price = { ...(min && { $gte: Number(min) }), ...(max && { $lte: Number(max) }) };
  const products = await Product.find(query).populate("vendor", "storeName slug rating").limit(60).sort("-createdAt");
  response.json(products);
}

export async function createProduct(request, response) {
  const product = await Product.create({ ...request.body, vendor: request.body.vendorId });
  request.app.get("io").to("admins").emit("product:approval_required", product);
  response.status(201).json(product);
}

export async function approveProduct(request, response) {
  const product = await Product.findByIdAndUpdate(request.params.id, { status: "approved" }, { new: true });
  response.json(product);
}
