<?php

declare(strict_types=1);

namespace MonsieurBiz\SyliusSearchPlugin\Provider;

use MonsieurBiz\SyliusSearchPlugin\Exception\ReadFileException;
use MonsieurBiz\SyliusSearchPlugin\Model\Config\FilesConfig;
use MonsieurBiz\SyliusSearchPlugin\Model\Config\FilesConfigInterface;

class SearchQueryProvider implements SearchQueryProviderInterface
{
    private FilesConfigInterface $filesConfig;

    public function __construct(array $files)
    {
        $this->filesConfig = new FilesConfig($files);
    }

    public function getSearchQuery(): string
    {
        return $this->getQuery($this->filesConfig->getSearchPath());
    }

    public function getInstantQuery(): string
    {
        return $this->getQuery($this->filesConfig->getInstantPath());
    }

    public function getTaxonQuery(): string
    {
        return $this->getQuery($this->filesConfig->getTaxonPath());
    }

    private function getQuery(string $path): string
    {
        $query = @file_get_contents($path);
        if (false === $query) {
            throw new ReadFileException(sprintf('Error while opening file "%s".', $path));
        }

        return $query;
    }
}
