<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Model\Exporter;

use Magento\Framework\DataObject;
use Magento\Framework\DataObjectFactory;
use Magento\Search\Model\QueryInterface;
use Magento\Store\Model\StoreManagerInterface;

/**
 *
 */
class DefaultSearchTermAdapter implements SearchTermAdapterInterface
{
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    private $storeManager;
    /**
     * @var \Magento\Store\Api\Data\StoreInterface[]
     */
    private $stores;
    /**
     * @var \Magento\Framework\DataObjectFactory
     */
    private $dataObjectFactory;

    /**
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Framework\DataObjectFactory $dataObjectFactory
     */
    public function __construct(StoreManagerInterface $storeManager, DataObjectFactory $dataObjectFactory)
    {
        $this->storeManager = $storeManager;
        $this->dataObjectFactory = $dataObjectFactory;
    }

    /**
     * @param \Magento\Search\Model\QueryInterface|\Magento\Search\Model\Query $query
     * @return \Magento\Framework\DataObject
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function adapt(QueryInterface $query): DataObject
    {
        return $this->dataObjectFactory->create([
            'data' => [
                '_id'      => $query->getId(),
                'redirect' => $query->getRedirect(),
                'store'    => $this->getStoreCode($query),
                'query_text' => $query->getQueryText()
            ]
        ]);
    }

    /**
     * @param \Magento\Search\Model\QueryInterface $query
     * @return string|null
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getStoreCode(QueryInterface $query): ?string
    {
        if ($this->stores === null) {
            $this->stores = $this->storeManager->getStores();
        }

        return $this->stores[$query->getStoreId()]->getData('code');
    }

}