<?php
declare(strict_types=1);

namespace Autogedal\Reduceri\Model;

use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Framework\App\CacheInterface;
use Magento\Framework\DB\Select;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Store\Model\StoreManagerInterface;
use Zend_Db_Expr;

class DiscountProvider
{
    private const CACHE_TAG = 'reduceri_discount';
    private const CACHE_TTL = 900; // 15 min

    public function __construct(
        private readonly CollectionFactory      $collectionFactory,
        private readonly CacheInterface         $cache,
        private readonly SerializerInterface    $serializer,
        private readonly StoreManagerInterface  $storeManager
    ) {}

    public function getStats(Category $category): array
    {
        $storeId  = (int) $this->storeManager->getStore()->getId();
        $cacheKey = self::CACHE_TAG . '_' . $category->getId() . '_' . $storeId;

        $cached = $this->cache->load($cacheKey);
        if ($cached !== false) {
            return $this->serializer->unserialize($cached);
        }

        $collection = $this->buildDiscountCollection($category);
        $count = $collection->getSize();

        $maxPct = 0;
        if ($count > 0) {
            $select = clone $collection->getSelect();
            $select->reset(Select::COLUMNS)
                   ->reset(Select::LIMIT_COUNT)
                   ->reset(Select::LIMIT_OFFSET)
                   ->columns(['max_pct' => new Zend_Db_Expr(
                       'MAX(ROUND((1 - price_index.final_price / NULLIF(price_index.price, 0)) * 100))'
                   )]);
            $maxPct = (int) $collection->getConnection()->fetchOne($select);
        }

        $stats = ['count' => $count, 'max_pct' => $maxPct];
        $this->cache->save(
            $this->serializer->serialize($stats),
            $cacheKey,
            [self::CACHE_TAG, Category::CACHE_TAG . '_' . $category->getId()],
            self::CACHE_TTL
        );

        return $stats;
    }

    public function buildDiscountCollection(Category $category): \Magento\Catalog\Model\ResourceModel\Product\Collection
    {
        $collection = $this->collectionFactory->create();
        $collection->addCategoryFilter($category);
        $collection->addAttributeToFilter('status', Status::STATUS_ENABLED);
        $collection->addAttributeToFilter('visibility', ['in' => [
            Visibility::VISIBILITY_IN_CATALOG,
            Visibility::VISIBILITY_BOTH,
        ]]);
        $collection->addStoreFilter();
        $collection->addPriceData();
        $collection->getSelect()->where('price_index.final_price < price_index.price');

        return $collection;
    }
}
