<?php

namespace Autogedal\CategoryReviews\Model;

use Autogedal\CategoryReviews\Helper\Data;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Framework\App\CacheInterface;
use Psr\Log\LoggerInterface;

class CategoryReviewsBackendLogic
{
    protected $storeManager;
    protected $cache;
    protected $productCollectionFactory;
    protected $logger;

    /**
     * @var  Data
     */
    protected $helper;

    public function __construct(
        Data $helper,
        StoreManagerInterface $storeManager,
        CollectionFactory $productCollectionFactory,
        CacheInterface $cache,
        LoggerInterface $logger
    ) {
        $this->helper = $helper;
        $this->storeManager = $storeManager;
        $this->productCollectionFactory = $productCollectionFactory;
        $this->cache = $cache;
        $this->logger = $logger;
    }

    public function clearCategoryCache($categoryId, $storeId = null)
    {
        if ($storeId === null) {
            foreach ($this->storeManager->getStores() as $store) {
                $this->clearCategoryCache($categoryId, $store->getId());
            }
            return;
        }

        $cacheKey = Data::CACHE_TAG . '_' . $categoryId . '_' . $storeId;
        $this->cache->remove($cacheKey);
    }

    public function getCategoryPriceStatsFromOpenSearch($category)
    {
        $categoryId = $category->getId();
        $storeId = $this->storeManager->getStore()->getId();
        
        $cacheKey = 'category_price_stats_' . $categoryId . '_' . $storeId;
        
        $cachedResult = $this->cache->load($cacheKey);
        if ($cachedResult) {
            $decodedResult = json_decode($cachedResult, true);
            if ($decodedResult && is_array($decodedResult)) {
                return $decodedResult;
            }
        }

        try {
            $collection = $this->productCollectionFactory->create();
            
            $collection->setStoreId($storeId);
            $collection->addCategoryFilter($category);
            $collection->addAttributeToFilter('visibility', [
                'in' => [
                    Visibility::VISIBILITY_IN_CATALOG,
                    Visibility::VISIBILITY_IN_SEARCH, 
                    Visibility::VISIBILITY_BOTH
                ]
            ]);
            
            $collection->addAttributeToFilter('status', Status::STATUS_ENABLED);
            $collection->addPriceData();
            $collection->getSelect()->where('price_index.min_price > 0');

            $collection->getSelect()->reset(\Magento\Framework\DB\Select::COLUMNS);
            $collection->getSelect()->columns([
                'min_price' => 'MIN(price_index.min_price)',
                'max_price' => 'MAX(price_index.max_price)', 
                'product_count' => 'COUNT(DISTINCT e.entity_id)'
            ]);

            $connection = $collection->getConnection();
            $result = $connection->fetchRow($collection->getSelect());
            
            if (!$result || !$result['product_count']) {
                $priceStats = ['lowPrice' => 0, 'highPrice' => 0, 'offerCount' => 0];
            } else {
                $priceStats = [
                    'lowPrice' => $result['min_price'] ? (float)$result['min_price'] : 0,
                    'highPrice' => $result['max_price'] ? (float)$result['max_price'] : 0,
                    'offerCount' => $result['product_count'] ? (int)$result['product_count'] : 0
                ];
            }

            $this->cache->save(
                json_encode($priceStats),
                $cacheKey,
                ['catalog_product', 'catalog_category_product', 'category_' . $categoryId],
                3600
            );

            return $priceStats;

        } catch (\Exception $e) {
            $this->logger->error('Error in CategoryReviews getCategoryPriceStatsFromOpenSearch: ' . $e->getMessage());
        }
    }
}
