<?php

declare(strict_types=1);

namespace App\Integrations\Copyscape;

use Exception;
use GuzzleHttp\Client as GuzzleClient;
use SimpleXMLElement;
use Symfony\Component\Messenger\MessageBusInterface;

final class GuzzleHandler
{
    private $client;
    private $url = 'http://www.copyscape.com/api';
    private $user;
    private $key;
    /**
     * @var MessageBusInterface
     */
    private $messageBus;

    public function __construct(GuzzleClient $client, string $user, string $key, MessageBusInterface $messageBus)
    {
        $this->client = $client;
        $this->messageBus = $messageBus;
        $this->user = $user;
        $this->key = $key;
    }

    /**
     * @param RequestInterface $request
     *
     * @return SimpleXMLElement
     *
     * @throws Exception
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function makeRequest(RequestInterface $request)
    {
        if ($request instanceof RemainingRequest) {
            $requestUrl = sprintf('%s?%s&%s', $this->url, http_build_query(['u' => $this->user, 'k' => $this->key]),
                $request->queryString());

            $response = $this->client->request($request->method(), $requestUrl);
        } elseif ($request instanceof CSearchRequest || $request instanceof TestCSearchRequest) {
            $requestUrl = sprintf('%s?%s&%s', $this->url, http_build_query(['u' => $this->user, 'k' => $this->key]), $request->queryString());
            $response = $this->client->request($request->method(), $requestUrl, $request->body());
        }

        return simplexml_load_string((string) $response->getBody());
    }
}
