<?php

declare(strict_types=1);

namespace App\Domain\Manga\Infrastructure\ApiPlatform\State\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Domain\Manga\Application\Query\FindMangaMatchByFilename;
use App\Domain\Manga\Application\QueryHandler\FindMangaMatchByFilenameHandler;
use App\Domain\Manga\Infrastructure\ApiPlatform\Dto\FilenameMatchItem;
use App\Domain\Manga\Infrastructure\ApiPlatform\Resource\FindMangaMatchByFilenameResource;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

readonly class FindMangaMatchByFilenameStateProvider implements ProviderInterface
{
    public function __construct(
        private FindMangaMatchByFilenameHandler $handler
    ) {
    }

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): FindMangaMatchByFilenameResource
    {
        $filename = $context['filters']['filename'] ?? '';

        if (empty($filename)) {
            throw new BadRequestHttpException('Le nom de fichier est requis');
        }

        $query = new FindMangaMatchByFilename($filename);
        $response = $this->handler->handle($query);

        // Pour Get, on retourne directement la resource
        return new FindMangaMatchByFilenameResource(
            matches: array_map(
                fn ($match) => new FilenameMatchItem(
                    id: $match->id,
                    title: $match->title,
                    slug: $match->slug,
                    alternativeSlugs: $match->alternativeSlugs,
                    thumbnailUrl: $match->thumbnailUrl,
                    matchScore: $match->matchScore,
                    chapterNumber: $match->chapterNumber,
                    volumeNumber: $match->volumeNumber
                ),
                $response->matches
            ),
        );
    }
}
