<?php

declare(strict_types=1);

namespace External\PompoBundle\Overrides\GraphQL\Util;

use External\PompoBundle\Util\Order\PompoOrderUtil;
use KupShop\GraphQLBundle\ApiAdmin\Types\Order\Input\OrderUpdateInput;
use KupShop\GraphQLBundle\ApiAdmin\Types\Order\Response\OrderMutateResponse;
use KupShop\KupShopBundle\Util\ObjectUtil;
use Symfony\Contracts\Service\Attribute\Required;

class OrderUtil extends \KupShop\GraphQLBundle\ApiAdmin\Util\OrderUtil
{
    private ?PompoOrderUtil $pompoOrderUtil = null;

    #[Required]
    final public function setPompoOrderUtil(PompoOrderUtil $pompoOrderUtil): void
    {
        $this->pompoOrderUtil = $pompoOrderUtil;
    }

    public function updateOrder(OrderUpdateInput $input): OrderMutateResponse
    {
        return $this->withOrderOriginalStateCreation($input, function () use ($input) {
            return parent::updateOrder($input);
        });
    }

    private function withOrderOriginalStateCreation(OrderUpdateInput $input, callable $fn): mixed
    {
        try {
            $order = \Order::get($input->id);
        } catch (\InvalidArgumentException $e) {
            $order = null;
        }

        if ($order && ObjectUtil::isPropertyInitialized($input, 'items') && !empty($input->items)) {
            $originalStates = $order->getData('orderOriginalStates') ?: [];

            $originalState = [];
            foreach ($order->getItems() as $item) {
                if (!$item['id_product']) {
                    continue;
                }

                $originalState[$item->getId()] = $this->pompoOrderUtil->prepareSimpleOrderItem($item);
            }

            $originalStates[] = $originalState;

            $order->setData('orderOriginalStates', $originalStates);
            $order->setData('pompoCreateItemDiffFromLocalData', true);
        }

        return $fn();
    }
}
