<?php

namespace Myvetshop\Module\Clinique\Import\Serializer;

use Myvetshop\Module\Clinique\Import\Model\CartRuleModel;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;

class CartRuleModelNormalizer implements DenormalizerInterface
{
    /**
     * @param array<mixed> $context
     *
     * @return CartRuleModel
     */
    public function denormalize($data, $type, $format = null, array $context = [])
    {
        if (!\is_array($data)) {
            throw new \Exception('Invalid JSON data');
        }

        $ret = new CartRuleModel();

        $ret->email = $data['email'];
        $ret->name = $data['name'];
        $ret->dateFrom = \DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $data['date_from'])
            ?: new \DateTimeImmutable();
        $ret->dateTo = \DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $data['date_to'])
            ?: new \DateTimeImmutable();
        $ret->description = $data['description'];
        $ret->quantity = \intval($data['quantity']);
        $ret->code = $data['code'];
        $ret->reductionAmount = \floatval($data['reduction_amount']);
        $ret->active = \boolval($data['active']);
        $ret->dateAdd = \DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $data['date_add'])
            ?: new \DateTimeImmutable();

        return $ret;
    }

    public function supportsDenormalization($data, $type, $format = null)
    {
        return CartRuleModel::class === $type;
    }
}
