<?php

namespace App\Tmdb\Framework\Controller;

use App\Base\Util\ImdbMatcher;
use App\Tmdb\TmdbClient;
use App\Tmdb\TmdbResult;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

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,
        ]);
    }
}
