<?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 TmdbTvShowResultDenormalizer extends TmdbResultDenormalizer implements DenormalizerInterface
{
    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 (!in_array($data['first_air_date'], ['', null,])) {
            $airDate =  (new \DateTime($data['first_air_date']));
        } else {
            $airDate = null;
        }

        if (array_key_exists('seasons', $data)) {
            $result->numberSeasons = count($data['seasons']);
        }

        $result->title = $data['original_name'];
        $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::TvShow->value;

        if (is_array($result->episodes)) {
            $result->latestSeason = array_key_last($result->episodes);
        }

        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::TvShow->value;
    }

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