<?php

declare(strict_types=1);

namespace KupShop\UserAddressesBundle\Util;

use KupShop\GraphQLBundle\EventListener\JsShopRefreshListener;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

class UserAddressesCartUtil
{
    public function __construct(
        protected readonly \Cart $cart,
        protected readonly UserAddressesUtil $userAddressesUtil,
        protected readonly SessionInterface $session,
    ) {
    }

    public function saveAddressToCart(?int $id): void
    {
        $this->cart->load();
        $this->cart->setData('user_address_id', $id);

        if ($id === null || $id === 0) {
            return;
        }

        $address = $this->userAddressesUtil->getDeliveryAddress($id);
        if ($address !== null) {
            $this->cart->fetchAddresses();
            $this->cart->updateAddresses($this->cart->invoice, $address->getCartAddressArray());
            $this->cart->save();

            $this->cart->invalidatePurchaseState();
            $this->session->set(JsShopRefreshListener::SESSION_NAME, true);
        }
    }
}
