<?php

namespace App\Torrentio\Client;

use Carbon\Carbon;
use GuzzleHttp\Client as GuzzleClient;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Contracts\Cache\TagAwareCacheInterface;

class HttpClient
{
    private GuzzleClient $client;

    private string $baseUrl = 'https://torrentio.strem.fun/realdebrid=%s/';

    public function __construct(
        #[Autowire(env: 'REAL_DEBRID_KEY')] private string $realDebridKey,
        private TagAwareCacheInterface $cache,
        private LoggerInterface $logger,
    ) {
        $this->client = new GuzzleClient([
            'base_uri' => sprintf($this->baseUrl, $this->realDebridKey),
        ]);
    }

    public function get(string $imdbId, array $cacheTags = []): array
    {
        $cacheKey = str_replace(":", ".", "torrentio.{$imdbId}");

        return $this->cache->get($cacheKey, function (ItemInterface $item) use ($imdbId, $cacheTags) {
            $item->expiresAt(Carbon::now()->addHour()->setMinute(0)->setSecond(0));
            if (count($cacheTags) > 0) {
                $item->tag($cacheTags);
            }
            try {
                $response = $this->client->get("stream/movie/$imdbId.json");
                return json_decode(
                    $response->getBody()->getContents(),
                    true
                );
            } catch (\Throwable $exception) {
                dd($exception);
                if ($exception->getCode() === 429) {
                    $this->logger->warning("> [TorrentioClient] Rate limit exceeded");
                    return null;
                }
            }

            $this->logger->error("> [TorrentioClient] Request error: " . $response->getStatusCode() . " - " . $response->getBody()->getContents());
            return [];
        });
    }
}
