<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Model;

use FiloBlu\Refilo\Api\SearchManagementInterface;
use Magento\Search\Model\QueryFactory;
use Magento\Store\Model\StoreManagerInterface;

/**
 *
 */
class SearchManagement implements SearchManagementInterface
{
    /**
     * @var \Magento\Search\Model\QueryFactory
     */
    private $queryFactory;
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    private $storeManager;

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

    /**
     * @throws \Magento\Framework\Exception\LocalizedException
     * @throws \Exception
     */
    public function updateSearchTerm(string $searchTerm, string $store, int $results)
    {
        $storeId = $this->storeManager->getStore($store)->getId();

        /** @var \Magento\Search\Model\Query $query */
        $query = $this->queryFactory->create();
        $query->setStoreId($storeId);

        $result = $query->loadByQueryText($searchTerm);

        if (!$result->getId()) {
            $result->setQueryText($searchTerm);
            $result->setStoreId($storeId);
            $result->setPopularity(0);
        }

        $result->setNumResults($results);
        $result->setPopularity($result->getPopularity() + 1);
        $result->save();
    }
}