<?php

namespace App\Search\Framework\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\Search\Action\Result\RedirectToMediaResult;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Attribute\Route;

final class WebController 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());

        if ($results instanceof RedirectToMediaResult) {
            return $this->redirectToRoute('app_search_result', [
                'mediaType' => $results->mediaType,
                'imdbId' => $results->imdbId,
            ]);
        }

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

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

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