const Customers = require("../../models/Customers");
const ProductReviews = require("../../models/DetailProductReviews");
const SellerCompanyReviews = require("../../models/DetailSellerReviews");
const { Sequelize } = require("sequelize");
const Products = require("../../models/Products");

exports.buildProductReviews = async (productIds = []) => {
  try {
    const productReviews = await ProductReviews.findAll({
      where: {
        product_id: productIds,
      },
      include: [
        {
          model: Customers,
          as: "customer",
          attributes: ["id", "first_name", "last_name"],
        },
      ],
      order: [["timestamp", "DESC"]],
    });

    const reviews = productReviews.map((review) => ({
      customer_id: review.customer?.id,
      customer_name: `${review.customer?.first_name} ${review.customer?.last_name}`,
      rate: review.rate,
      review: review.reviews,
      reference_no: review.reference_no,
      timestamp: review.timestamp,
    }));

    const averageRating =
      productReviews.length > 0
        ? (
            productReviews.reduce((acc, review) => acc + review.rate, 0) /
            productReviews.length
          ).toFixed(2)
        : null;

    return {
      average_rating: averageRating,
      total_reviews: productReviews.length,
      reviews,
    };
  } catch (err) {
    console.error("Error in buildProductReviews:", err);
    return { error: "Something went wrong", details: err.message };
  }
};
exports.buildSellerReviews = async (sellerId) => {
  try {
    const sellerReviews = await SellerCompanyReviews.findAll({
      where: {
        seller_id: sellerId,
      },
      include: [
        {
          model: Customers,
          as: "customer",
          attributes: ["id", "first_name", "last_name"],
        },
      ],
      order: [["timestamp", "DESC"]],
    });

    const reviews = sellerReviews.map((review) => ({
      customer_id: review.customer?.id || null,
      customer_name: `${review.customer?.first_name || ""} ${
        review.customer?.last_name || ""
      }`.trim(),
      rate: review.rate,
      review: review.review,
      timestamp: review.timestamp,
    }));

    const averageRating =
      sellerReviews.length > 0
        ? (
            sellerReviews.reduce((sum, r) => sum + r.rate, 0) /
            sellerReviews.length
          ).toFixed(2)
        : null;

    return {
      average_rating: averageRating,
      total_reviews: sellerReviews.length,
      reviews,
    };
  } catch (err) {
    console.error("Error in buildSellerReviews:", err);
    return { error: "Something went wrong", details: err.message };
  }
};

exports.postCustomerRating = async (req, res, next) => {
  try {
    const { customerId } = req;

    const { reference_no, product_id, rating, comment } = req.body;

    if (!product_id || !rating || !comment || !reference_no)
      return res
        .status(200)
        .json({ success: false, message: "Missing required parameters" });

    const product = await Products.findOne({
      where: {
        id: product_id,
      },
    });

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

    const createdRating = await ProductReviews.create({
      product_id,
      customer_id: customerId,
      rate: rating,
      reviews: comment,
      reference_no: reference_no,
      timestamp: new Date(),
    });

    res.status(200).json({ success: true, rating: createdRating });
  } catch (err) {
    next(err);
  }
};
