<?php
namespace Banyo\CustomProduct\Plugin\Review;

use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Review\Model\ResourceModel\Review\Summary as Subject;

class Summary
{
    /**
     * Check if review_summary join already exists before adding it
     *
     * @param Subject $subject
     * @param callable $proceed
     * @param Collection $productCollection
     * @param int $storeId
     * @param string $entityCode
     * @return Subject
     */
    public function aroundAppendSummaryFieldsToCollection(
        Subject $subject,
        callable $proceed,
        Collection $productCollection,
        int $storeId,
        string $entityCode
    ) {
        // Check if the join already exists in the collection
        $joinParts = $productCollection->getSelect()->getPart(\Zend_Db_Select::FROM);

        if (isset($joinParts['review_summary'])) {
            // Join already exists, don't add it again
            return $subject;
        }

        // Join doesn't exist, proceed with the original method
        return $proceed($productCollection, $storeId, $entityCode);
    }
}
