<?php

namespace AutoAdmin\Bundle\Media\Serializer;

use AutoAdmin\Bundle\Media\Model\Library\BaseMediaInterface;
use AutoAdmin\Bundle\Media\Model\Library\BaseMediaTranslationInterface;
use AutoAdmin\Bundle\Media\Model\Library\FileMediaInterface;
use AutoAdmin\Bundle\Media\Model\Library\FileMediaTranslationInterface;
use AutoAdmin\Bundle\Media\Model\Library\ImageMediaInterface;
use AutoAdmin\Bundle\Media\Model\Library\ImageMediaTranslationInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class MediaNormalizer implements NormalizerInterface
{
    public function __construct(
        private readonly NormalizerInterface $objectNormalizer,
    ) {
    }

    public function normalize(mixed $object, string $format = null, array $context = []): array
    {
        $data = $this->objectNormalizer->normalize($object, $format, $context);

        if ($object instanceof FileMediaInterface) {
            // do nothing, handled via groups
        } elseif ($object instanceof ImageMediaInterface) {
            // do nothing, handled via groups
        }

        /** @var BaseMediaTranslationInterface $tr */
        $tr = $object->getCurrentTranslation();
        if ($tr instanceof FileMediaTranslationInterface) {
            $data["fileName"] = $tr->getFileName();
            $data["title"] = $tr->getTitle();
        }
        if ($tr instanceof ImageMediaTranslationInterface) {
            $data["alt"] = $tr->getAlt();
        }

        return $data;
    }

    public function supportsNormalization($data, string $format = null, array $context = []): bool
    {
        return $data instanceof BaseMediaInterface && $format === 'json';
    }

    public function getSupportedTypes(?string $format): array
    {
        return [
            BaseMediaInterface::class => true,
        ];
    }
}
