<?php

declare(strict_types=1);

namespace App\Integrations\Majestic;

use App\Message\MajesticReportFetched;
use GuzzleHttp\Client as GuzzleClient;
use Symfony\Component\Messenger\MessageBusInterface;

final class GuzzleReportHandler implements ReportHandler
{
    private $client;
    /**
     * @var string
     */
    private $majesticUrl;
    /**
     * @var string
     */
    private $majesticApiKey;
    /**
     * @var MessageBusInterface
     */
    private $messageBus;

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

    /**
     * @param Request $request
     *
     * @return Response
     *
     * @throws \Exception
     */
    public function report(Request $request): Response
    {
        $requestUrl = sprintf('%sapi/json?app_api_key=%s&cmd=GetIndexItemInfo&items=1&item0=%s&datasource=fresh&DesiredTopics=3', $this->majesticUrl, $this->majesticApiKey, $request->getUrl());

        $response = $this->client->get($requestUrl);

        $data = json_decode((string) $response->getBody());
        $data = $data->DataTables->Results->Data[0];

        $this->messageBus->dispatch(new MajesticReportFetched($request->getUrl(), $requestUrl, new \DateTimeImmutable(), (string) $response->getBody()));

        return Response::from($request->getUrl(), (int) $data->TrustFlow, (int) $data->CitationFlow);
    }
}
