<?php

declare(strict_types=1);

namespace App\Tests\Module\Commercial\Unit;

use ApiPlatform\Metadata\IriConverterInterface;
use App\Module\Commercial\Infrastructure\ApiPlatform\Serializer\CategoryReferenceDenormalizer;
use App\Shared\Domain\Contract\CategoryInterface;
use PHPUnit\Framework\TestCase;
use stdClass;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;

/**
 * Tests unitaires du CategoryReferenceDenormalizer : resolution d'un IRI vers
 * une Category concrete, et rejet explicite d'un IRI pointant sur une autre
 * ressource (au lieu d'un null silencieux qui perdrait la reference).
 *
 * @internal
 */
final class CategoryReferenceDenormalizerTest extends TestCase
{
    public function testResolvesCategoryIri(): void
    {
        $category     = $this->createStub(CategoryInterface::class);
        $iriConverter = $this->createMock(IriConverterInterface::class);
        $iriConverter->method('getResourceFromIri')->willReturn($category);

        $denormalizer = new CategoryReferenceDenormalizer($iriConverter);

        self::assertSame(
            $category,
            $denormalizer->denormalize('/api/categories/1', CategoryInterface::class),
        );
    }

    public function testRejectsIriOfWrongType(): void
    {
        // Bug review ERP-55 : un IRI syntaxiquement valide mais pointant sur une
        // autre ressource (ex: /api/clients/5) doit lever une exception au lieu
        // d'etre silencieusement ignore.
        $iriConverter = $this->createMock(IriConverterInterface::class);
        $iriConverter->method('getResourceFromIri')->willReturn(new stdClass());

        $denormalizer = new CategoryReferenceDenormalizer($iriConverter);

        $this->expectException(UnexpectedValueException::class);
        $denormalizer->denormalize('/api/clients/5', CategoryInterface::class);
    }

    public function testReturnsNullForEmptyData(): void
    {
        // Valeur vide deleguee par l'ArrayDenormalizer : aucun appel a
        // l'IriConverter, retour null.
        $iriConverter = $this->createMock(IriConverterInterface::class);
        $iriConverter->expects(self::never())->method('getResourceFromIri');

        $denormalizer = new CategoryReferenceDenormalizer($iriConverter);

        self::assertNull($denormalizer->denormalize('', CategoryInterface::class));
    }
}
