<?php

declare(strict_types=1);

namespace External\HannahBundle\Feed\Wrapper;

use KupShop\KupShopBundle\Util\Functional\Mapping;

class SellerWrapper extends \KupShop\SellerBundle\Feed\Wrapper\SellerWrapper
{
    /** ID v SAPu */
    public function field_id_sap(): ?int
    {
        $this->fetchSapIds();

        return $this->object->id_sap ?? null;
    }

    private function fetchSapIds(): void
    {
        if (!isset($this->sellers->_sap_ids_fetched)) {
            $stores = Mapping::mapKeys(sqlQueryBuilder()
                ->select('*')
                ->from('sap_stores')
                ->execute()->fetchAllAssociative(), fn ($k, $v) => [(int) $v['id_store'], (int) $v['id_sap']]);

            foreach ($this->sellers as &$seller) {
                $seller->id_sap = $stores[$seller->id_store] ?? null;
            }

            $this->sellers->_sap_ids_fetched = true;
        }
    }
}
