<?php

declare(strict_types=1);

namespace App\Shared\Infrastructure\ApiPlatform\Serializer;

use ApiPlatform\Metadata\IriConverterInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Throwable;

use function array_key_exists;
use function is_string;

/**
 * Modular monolith: cross-module relations are typed with a Shared\Domain\Contract
 * interface (e.g. UserInterface, TaskTagInterface) instead of the concrete entity,
 * to keep modules decoupled. Doctrine maps those back to the concrete entity through
 * resolve_target_entities.
 *
 * API Platform denormalizes *single* interface relations fine (the concrete class is
 * derived from the IRI), but blows up on *collections*: the collection value type stays
 * the interface, which is not a registered API resource, so no normalizer supports it
 * and the request fails with NotNormalizableValueException.
 *
 * This denormalizer bridges that gap for every contract interface, reusing Doctrine's
 * resolve_target_entities mapping (no per-entity config):
 *  - a string value is an IRI -> resolved through the IriConverter
 *  - an array value is an embedded object -> denormalized into the concrete entity
 */
final class ContractRelationDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
    use DenormalizerAwareTrait;

    private const CONTRACT_NAMESPACE = 'App\Shared\Domain\Contract\\';

    /** @var array<string, ?class-string> */
    private array $resolved = [];

    public function __construct(
        private readonly IriConverterInterface $iriConverter,
        private readonly EntityManagerInterface $entityManager,
    ) {}

    public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
    {
        return null !== $this->concreteClassFor($type);
    }

    public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): ?object
    {
        $concrete = $this->concreteClassFor($type);
        if (null === $concrete) {
            return null;
        }

        if (is_string($data)) {
            return $this->iriConverter->getResourceFromIri($data, $context);
        }

        // Embedded object payload: denormalize into the resolved concrete entity.
        return $this->denormalizer->denormalize($data, $concrete, $format, $context);
    }

    public function getSupportedTypes(?string $format): array
    {
        // Support depends on the runtime-resolved Doctrine mapping, so it cannot be
        // statically cached by the serializer.
        return ['object' => false];
    }

    /**
     * @return ?class-string the concrete entity a contract interface resolves to, or null
     */
    private function concreteClassFor(string $type): ?string
    {
        if (array_key_exists($type, $this->resolved)) {
            return $this->resolved[$type];
        }

        if (!str_starts_with($type, self::CONTRACT_NAMESPACE) || !interface_exists($type)) {
            return $this->resolved[$type] = null;
        }

        try {
            $name = $this->entityManager->getClassMetadata($type)->getName();
        } catch (Throwable) {
            // Not a Doctrine-mapped (resolve_target_entities) interface.
            return $this->resolved[$type] = null;
        }

        return $this->resolved[$type] = ($name !== $type ? $name : null);
    }
}
