<?php

declare(strict_types=1);

/**
 * @author Amasty Team
 * @copyright Copyright (c) Amasty (https://www.amasty.com)
 * @package Advanced Product Reviews Base for Magento 2
 */

namespace Amasty\AdvancedReview\Model\ResourceModel\Review;

use Magento\Framework\App\ResourceConnection;

class RatingSummary
{
    public const COUNT_KEY = 'count';
    public const SUMMARY_KEY = 'summary';
    public const REVIEW_ID = 'review_id';

    /**
     * @var ResourceConnection
     */
    private $resourceConnection;

    public function __construct(ResourceConnection $resourceConnection)
    {
        $this->resourceConnection = $resourceConnection;
    }

    /**
     * @param int[] $reviewIds
     * @param int $storeId
     * @return array{int: array{'count': int}}
     */
    public function getSummaryForReviews(array $reviewIds, int $storeId): array
    {
        $connection = $this->resourceConnection->getConnection();
        $select = $connection
            ->select()
            ->from(
                ['rating_vote' => $this->resourceConnection->getTableName('rating_option_vote')],
                [
                    self::REVIEW_ID,
                    self::SUMMARY_KEY => new \Zend_Db_Expr('FLOOR(AVG(value))')
                ]
            )->joinInner(
                ['review_store' => $this->resourceConnection->getTableName('review_store')],
                'rating_vote.review_id = review_store.review_id',
                ['review_store.store_id']
            )
            ->where('rating_vote.review_id IN(?)', $reviewIds)
            ->where('review_store.store_id = ?', $storeId)
            ->group('rating_vote.review_id');

        $rating = $connection
            ->select()
            ->from(
                $select,
                [
                    self::SUMMARY_KEY,
                    self::COUNT_KEY => new \Zend_Db_Expr('COUNT(' . self::SUMMARY_KEY . ')')
                ]
            )
            ->group(self::SUMMARY_KEY);

        return $connection->fetchAssoc($rating) ?: [];
    }
}
