<?php

namespace Comitium5\DesignerBundle\Repository\Search;

use Comitium5\DesignerBundle\Adapter\Search\ExternalDbClient;
use Comitium5\DesignerBundle\Model\Interfaces\SearchClientInterface;
use Comitium5\DesignerBundle\ValueObjects\ExternalDbResultObject;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Class ExternalDbRepository
 *
 * @author David Carrascosa <david@bab-soft.com>
 * @package Comitium5\DesignerBundle\Repository\Search
 */
class ExternalDbRepository
{
    /**
     * @var SearchClientInterface
     */
    protected $searchClientInterface;

    /**
     * ElasticSearchRepository constructor.
     *
     * @param SearchClientInterface $searchClientInterface
     */
    public function __construct(
        SearchClientInterface $searchClientInterface
    ) {
        $this->searchClientInterface = $searchClientInterface;
    }

    /**
     * @param string $term
     * @param array $suggestQuery
     *
     * @return ExternalDbResultObject
     */
    public function search(string $term, array $suggestQuery): ExternalDbResultObject
    {
        /**
         * @var ExternalDbClient
         */
        $connection = $this
            ->searchClientInterface
            ->getClient();

        $query = preg_replace('/:[a-zA-Z0-9]+/', $term, $suggestQuery["query"]);

        $connection->query($query);
        $stmt = $connection->prepare($query);
        $success = $stmt->execute();

        if ($success !== true) {
            return new ExternalDbResultObject(
                [],
                JsonResponse::HTTP_BAD_REQUEST
            );
        }

        $results = $stmt->fetchAll();

        $connection->close();

        $results = !is_array($results) ? [] : $results;

        return new ExternalDbResultObject(
            $results,
            !count($results) ?
                JsonResponse::HTTP_NO_CONTENT :
                JsonResponse::HTTP_OK
        );
    }
}