<?php

namespace App\Controller;

use App\Search\Action\Handler\GetMediaInfoHandler;
use App\Search\Action\Handler\SearchHandler;
use App\Search\Action\Input\GetMediaInfoInput;
use App\Search\Action\Input\SearchInput;
use App\Tmdb\TmdbResult;
use App\Torrentio\Action\Command\GetMovieOptionsCommand;
use App\Torrentio\Action\Command\GetTvShowOptionsCommand;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Attribute\Route;

final class SearchController extends AbstractController
{
    public function __construct(
        private SearchHandler $searchHandler,
        private GetMediaInfoHandler $getMediaInfoHandler,
        private MessageBusInterface $bus,
    ) {}

    #[Route('/search', name: 'app_search', methods: ['GET'])]
    public function search(
        SearchInput $searchInput,
    ): Response {
        $results = $this->searchHandler->handle($searchInput->toCommand());

        return $this->render('search/results.html.twig', [
            'results' => $results,
        ]);
    }

    #[Route('/result/{mediaType}/{imdbId}/{season}', name: 'app_search_result')]
    public function result(
        GetMediaInfoInput $input,
        ?int $season = null,
    ): Response {
        $result = $this->getMediaInfoHandler->handle($input->toCommand());

//        $this->warmDownloadOptionCache($result->media);

        return $this->render('search/result.html.twig', [
            'results' => $result,
            'filter' => [
                'resolution' => '',
                'codec' => '',
                'provider' => '',
                'language' => '',
                'season' => 1,
                'episode' => ''
            ]
        ]);
    }

    private function warmDownloadOptionCache(TmdbResult $result)
    {
        if ($result->mediaType === 'tvshows') {
            // dispatches a job to get the download options
            // for each episode and load them in cache
            foreach ($result->episodes as $season => $episodes) {
                // Only do the first 2 seasons, so we reduce
                // getting rate-limited by Torrentio
                if ($season > 2) {
                    return;
                }
                foreach ($episodes as $episode) {
                    $this->bus->dispatch(new GetTvShowOptionsCommand(
                        tmdbId: $result->tmdbId,
                        imdbId: $result->imdbId,
                        season: $season,
                        episode: $episode['episode_number'],
                    ));
                }
            }
        } elseif ($result->mediaType === 'movies') {
            $this->bus->dispatch(new GetMovieOptionsCommand(
                $result->tmdbId,
                $result->imdbId,
            ));
        }
    }
}
