<?php

namespace App\Tmdb\Framework\Controller;

use App\Base\Enum\MediaType;
use App\Base\Util\ImdbMatcher;
use App\Library\Action\Result\LibrarySearchResult;
use App\Tmdb\TmdbClient;
use App\Tmdb\TmdbMovieGenre;
use App\Tmdb\TmdbResult;
use App\Tmdb\TmdbTvShowGenre;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\UX\Turbo\TurboBundle;

class ApiController extends AbstractController
{
    #[Route('/api/tmdb/ajax-search', name: 'api_tmdb_ajax_search', methods: ['GET'])]
    public function test(TmdbClient $tmdb, Request $request): Response
    {
        $results = [];

        $term = $request->query->get('query') ?? null;
        $term = trim($term);

        if (null !== $term) {
            if (ImdbMatcher::isMatch($term)) {
                $tmdbResult = $tmdb->search($term);
                $results = [
                    [
                        'data' => $tmdbResult,
                        'text' => $tmdbResult->title,
                        'value' => "$tmdbResult->mediaType|$tmdbResult->imdbId",
                    ]
                ];
            } else {
                $tmdbResults = $tmdb->search($term);
                foreach ($tmdbResults as $tmdbResult) {
                    /** @var TmdbResult $tmdbResult */
                    $results[] = [
                        'data' => $tmdbResult,
                        'text' => $tmdbResult->title,
                        'value' => "$tmdbResult->mediaType|$tmdbResult->imdbId",
                    ];
                }
            }
        }

        return $this->json([
            'results' => $results,
        ]);
    }

    #[Route('/api/tmdb/watch-providers/{mediaType}/{tmdbId}', name: 'api.tmdb.watch_providers', methods: ['GET'])]
    public function watchProviders(string $mediaType, string $tmdbId, Request $request, TmdbClient $tmdb)
    {
        $result = $tmdb->watchProviders($tmdbId, $mediaType);
        if ($request->headers->get('Turbo-Frame')) {
            return $this->sendFragmentResponse(['providers' => $result], $request);
        }

        return $this->json($result);
    }

    #[Route('/api/tmdb/genre/{mediaType}/{genreId}', name: 'api.tmdb.genre', methods: ['GET'])]
    public function genreResults(string $mediaType, string $genreId, Request $request, TmdbClient $tmdb)
    {
        $genre = TmdbMovieGenre::from($genreId);
        $results['media_type'] = $mediaType;
        $results['genre'] = $genre->name;
        $results['genre_id'] = $genre->value;
        $results['media'] = match($mediaType) {
            MediaType::Movie->value => $tmdb->discoverMovies(
                [TmdbMovieGenre::from($genre->value)],
            ),
            MediaType::TvShow->value => $tmdb->discoverTvShows(
                [TmdbTvShowGenre::from($genreId)]
            )
        };
        if ($request->headers->get('Turbo-Frame')) {
            return $this->sendFragmentResponse(['result' => $results], $request);
        }

        return $this->json($results);
    }

    private function sendFragmentResponse(mixed $result, Request $request): Response
    {
        $request->setRequestFormat(TurboBundle::STREAM_FORMAT);
        return $this->renderBlock(
            'discover/fragments.html.twig',
            $request->query->get('block'),
            [
                'result' => $result,
                'target' => $request->query->get('target')
            ]
        );
    }
}
