<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Remote\Entity\Provider;

use FiloBlu\Refilo\Helper\Catalog\CategoryHelper;
use FiloBlu\Refilo\Remote\Entity\CategoriesProduct;
use FiloBlu\Refilo\Remote\Entity\EntityProviderInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Select;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Api\Data\WebsiteInterface;
use Magento\Store\Model\StoreManagerInterface;
use Zend_Db;

use function count;

/**
 * Class StockProvider
 * @package FiloBlu\Refilo\Remote\Entity\Provider
 */
class CategoriesProductProvider extends BaseProvider
{
    /** @var int */
    protected $website;

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

    /** @var StoreManagerInterface */
    private $storeManager;
    /**
     * @var \FiloBlu\Refilo\Helper\Catalog\CategoryHelper
     */
    private $categoryHelper;

    /**
     * CategoriesProductProvider constructor.
     * @param ResourceConnection $resourceConnection
     * @param \FiloBlu\Refilo\Helper\Catalog\CategoryHelper $categoryHelper
     * @param StoreManagerInterface $storeManager
     * @param ScopeConfigInterface $scopeConfig
     */
    public function __construct(

        CategoryHelper $categoryHelper,
        ResourceConnection $resourceConnection,
        StoreManagerInterface $storeManager,
        ScopeConfigInterface $scopeConfig
    ) {
        parent::__construct($scopeConfig);
        $this->resourceConnection = $resourceConnection;
        $this->storeManager = $storeManager;
        $this->categoryHelper = $categoryHelper;
    }

    /**
     *
     */
    #[\ReturnTypeWillChange]
    public function rewind()
    {
        $select = $this->getSelectForProducts();

        if (!empty($this->ids)) {
            $select->where('s.product_id IN (' . implode(',', $this->ids) . ')');
        }

        $items = $this->resourceConnection->getConnection()->fetchAll($select, [], Zend_Db::FETCH_ASSOC);
        $data = [];

        foreach ($items as $item) {
            $productId = (int)$item['product_id'];
            $data[$productId]['id'] = $productId;
            $data[$productId]['category_' . $item['category_id']] = (int)$item['position'];

            if (!isset($data[$productId]['categories'])) {
                $data[$productId]['categories'] = [];
            }

            $data[$productId]['categories'][] = (int)$item['category_id'];

            foreach (
                $this->categoryHelper->getIsAnchorCategories(
                    (int)$item['category_id']
                ) as $parentId => $position
            ) {
                $data[$productId]['categories'][] = $parentId;
                $data[$productId]['category_' . $parentId] = $this->categoryHelper->getProductPositionInsideCategory(
                    $productId,
                    $parentId
                );
            }
        }

        $this->items = array_map(static function ($item) {
            $item['categories'] = array_values(array_unique($item['categories']));
            return new CategoriesProduct($item);
        }, $data);

        if (!$this->hasReadHandler()) {
            return;
        }

        // TODO: Handle pagination
        $this->getReadHandler()->onRead($this->items, count($this->items), $this->getReadHandlerArguments());
    }

    /**
     * @return Select
     */
    protected function getSelectForProducts()
    {
        return $this->resourceConnection->getConnection()
            ->select()
            ->from(
                [
                    's' => 'catalog_category_product'
                ],
                [
                    'id' => 's.entity_id',
                    'category_id' => 's.category_id',
                    'product_id' => 's.product_id',
                    'position' => 's.position'
                ]
            );
    }

    /**
     * @param array $ids
     * @return $this|EntityProviderInterface
     */
    public function withIds(array $ids): EntityProviderInterface
    {
        $this->ids = $ids;
        return $this;
    }

    /**
     * @param StoreInterface $store
     * @return $this|EntityProviderInterface
     */
    public function forStore(StoreInterface $store): EntityProviderInterface
    {
        return $this;
    }

    /**
     * @param WebsiteInterface $website
     * @return $this|EntityProviderInterface
     */
    public function forWebsite(WebsiteInterface $website): EntityProviderInterface
    {
        return $this;
    }
}
