const {
  productVariationBuilder,
} = require("../../helpers/productWithVariationBuilder");
const {
  buildProductReviews,
  buildSellerReviews,
} = require("./productReviews.controller");

const getAllProductIds = (product) => {
  if (!product) return [];

  const ids = [product.id].filter(Boolean);

  product.variations?.forEach((v) => {
    ids.push(v.id);
    v.sub_variations?.forEach((sv) => ids.push(sv.id));
  });

  return ids.filter(Boolean);
};

exports.postSearchProductById = async (req, res, next) => {
  try {
    const { id } = req.body;

    if (!id)
      return res
        .status(200)
        .json({ success: false, message: "Invalid product id" });

    const product = await productVariationBuilder(id);
    const allProductIds = getAllProductIds(product);

    const productReviews = await buildProductReviews(allProductIds);

    if (product && product.error) {
      return res.status(200).json({
        success: false,
        message: product.error,
        details: product.details,
      });
    }
    if (productReviews && productReviews.error) {
      return res.status(200).json({
        success: false,
        message: productReviews.error,
        details: productReviews.details,
      });
    }

    let sellerReviews = null;

    if (product && product.seller && product.seller.id) {
      const _sellerReviews = await buildSellerReviews(product.seller.id);

      if (_sellerReviews && _sellerReviews.error) {
        return res.status(200).json({
          success: false,
          message: _sellerReviews.error,
          details: _sellerReviews.details,
        });
      }

      sellerReviews = _sellerReviews;
    }

    res.status(200).json({
      success: true,
      _p: product,
      _r: productReviews,
      _s: sellerReviews,
    });
  } catch (err) {
    next(err);
  }
};
