<?php

declare(strict_types=1);

namespace KupShop\CatalogBundle\Util;

use KupShop\CatalogBundle\Entity\Variation;
use KupShop\CatalogBundle\Util\Serializer\VariationEntityFastSerializer;
use KupShop\KupShopBundle\Util\Entity\EntityUtil;
use KupShop\KupShopBundle\Wrapper\PriceWrapper;

class VariationsEntityUtil
{
    public function __construct(
        private readonly EntityUtil $entityUtil,
        private readonly VariationEntityFastSerializer $variationEntitySerializer,
    ) {
    }

    /**
     * @throws \Symfony\Component\Serializer\Exception\ExceptionInterface
     */
    public function createEntityFromArray(array $variation): Variation
    {
        $this->formatPrices($variation);
        $this->formatInStore($variation);
        $variation['values'] = $variation['combination'];

        try {
            return $this->variationEntitySerializer->denormalize($variation);
        } catch (\Throwable $e) {
            // TODO: remove catch when variationEntitySerializer turns out to work with no problems
            \Sentry\captureException($e);

            return $this->entityUtil->createEntity($variation, Variation::class);
        }
    }

    protected function formatPrices(array &$variation): void
    {
        $variation['price'] = PriceWrapper::unwrap($variation['productPrice']);
        $variation['price_for_discount'] = PriceWrapper::unwrap($variation['price_for_discount']);
        unset($variation['price_common']);
    }

    protected function formatInStore(array &$variation): void
    {
        if (array_key_exists('in_store_variation', $variation)) {
            $variation['in_store'] = (int) $variation['in_store_variation'];
        } else {
            $variation['in_store'] = (int) $variation['in_store'];
        }

        $variation['in_store_suppliers'] = isset($variation['in_store_suppliers'])
            ? (int) $variation['in_store_suppliers']
            : null;
    }
}
