<?php

namespace App\Tmdb\Framework\Controller;

use App\Tmdb\Tmdb;
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(Tmdb $tmdb, Request $request): Response
    {
        $results = [];

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

        if (null !== $term) {
            $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,
        ]);
    }
}
