<?php

declare(strict_types=1);

namespace KupShop\SellerBundle\SellerList;

use Doctrine\Common\Collections\ArrayCollection;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\StringUtil;
use KupShop\SellerBundle\Utils\SellerMultiFetch;
use Symfony\Component\DependencyInjection\Attribute\Exclude;

/**
 * @method fetchSellersBlocks()
 * @method fetchSellersPhotos()
 * @method fetchSellersInStore(array $products)
 */
#[Exclude]
class SellerCollection extends ArrayCollection
{
    private SellerMultiFetch $multiFetch;

    protected function getMultiFetch()
    {
        if (!isset($this->multiFetch)) {
            $this->multiFetch = ServiceContainer::getService(SellerMultiFetch::class);
        }

        return $this->multiFetch;
    }

    public function __call($name, $arguments)
    {
        if (StringUtil::startsWith($name, 'fetch') && method_exists($this->getMultiFetch(), $name)) {
            $this->doFetchWithArrayReference($name, $arguments);

            return;
        }

        throw new \Exception("Undefined method '{$name}' called on '{$this}'");
    }

    /**
     * Because sellers multifetch uses reference $sellers so we need to update it like this.
     */
    private function doFetchWithArrayReference(string $name, mixed $arguments): void
    {
        $sellers = $this->toArray();

        // sellers is passed by reference
        $this->getMultiFetch()->{$name}($sellers, ...$arguments);

        // update collection with updated sellers
        foreach ($sellers as $key => $seller) {
            $this->set($key, $seller);
        }
    }
}
