<?php

namespace App\Tmdb\Framework\Serializer;

use App\Base\Enum\MediaType;
use App\Tmdb\TmdbResult;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class TmdbMovieResultDenormalizer extends TmdbResultDenormalizer implements DenormalizerInterface
{
    const POSTER_IMG_PATH = "https://image.tmdb.org/t/p/w500";

    public function __construct(
        #[Autowire(service: 'serializer.normalizer.object')]
        private readonly NormalizerInterface $normalizer,
    ) {
        parent::__construct($normalizer);
    }

    public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): TmdbResult|array|null
    {
        /** @var TmdbResult $result */
        $result = parent::denormalize($data, TmdbResult::class, $format, $context);

        if (array_key_exists('release_date', $data) && !in_array($data['release_date'], ['', null,])) {
            $airDate = (new \DateTime($data['release_date']));
        } else {
            $airDate = null;
        }

        $result->title = $data['original_title'];
        $result->premiereDate = $airDate;
        $result->poster = (null !== $data['poster_path']) ? self::POSTER_IMG_PATH . $data['poster_path'] : null;
        $result->year = (null !== $airDate) ? $airDate->format('Y') : null;
        $result->mediaType = MediaType::Movie->value;
        return $result;
    }

    public function supportsDenormalization(
        mixed $data,
        string $type,
        ?string $format = null,
        array $context = []
    ): bool {
        return array_key_exists('media_type', $context) &&
            $context['media_type'] === MediaType::Movie->value;
    }

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