<?php

namespace App\Search\Action\Handler;

use App\Search\Action\Result\RedirectToMediaResult;
use App\Search\Action\Result\SearchResult;
use App\Tmdb\TmdbClient;
use App\Tmdb\TmdbResult;
use OneToMany\RichBundle\Contract\CommandInterface;
use OneToMany\RichBundle\Contract\HandlerInterface;
use OneToMany\RichBundle\Contract\ResultInterface;

/*** @implements HandlerInterface<SearchResult> */
class SearchHandler implements HandlerInterface
{
    public function __construct(
        private TmdbClient $tmdb,
    ) {}

    public function handle(CommandInterface $command): ResultInterface
    {
        $result = $this->tmdb->search($command->term);
        if ($result instanceof TmdbResult) {
            return new RedirectToMediaResult(
                imdbId: $result->imdbId,
                mediaType: $result->mediaType,
            );
        }
        return new SearchResult(
            term: $command->term,
            results: $this->tmdb->search($command->term)
        );
    }
}
