<?php

declare(strict_types=1);

namespace KupShop\UserAddressesBundle\EventSubscriber;

use KupShop\KupShopBundle\Context\UserContext;
use KupShop\OrderingBundle\Event\CartEvent;
use KupShop\UserAddressesBundle\Entity\DeliveryAddressEntity;
use KupShop\UserAddressesBundle\Util\UserAddressesUtil;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Contracts\Service\Attribute\Required;

class CartSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            CartEvent::CHECK_CART => [
                ['checkCart', 200],
            ],
        ];
    }

    private UserAddressesUtil $userAddressesUtil;
    private UserContext $userContext;

    public function checkCart(CartEvent $event): void
    {
        $cart = $event->getCart();

        $address = $cart->getData('new_address');

        // Fields exists so we need to check if some required field is not empty
        if (empty($address['street'])) {
            return;
        }

        $createNew = $address['save'] ?? false;
        unset($address['save']);
        if ($createNew) {
            if ($userId = $this->userContext->getActiveId()) {
                $entity = (new DeliveryAddressEntity())->setName($address['name'] ?? '')
                    ->setSurname($address['surname'] ?? '')
                    ->setFirm($address['firm'] ?? '')
                    ->setStreet($address['street'] ?? '')
                    ->setCity($address['city'] ?? '')
                    ->setZip($address['zip'] ?? '')
                    ->setCountry($address['country'] ?? '')
                    ->setCurrency($address['currency'] ?? '')
                    ->setPhone($address['phone'] ?? '')
                    ->setState($address['state'] ?? '')
                    ->setEmail($address['email'] ?? '')
                    ->setCustomAddress($address['custom_address'] ?? '')
                    ->setIdUser($userId);

                $this->userAddressesUtil->saveDeliveryAddress($entity);
            }
        }

        $cart->updateAddresses($cart->invoice, $address);
    }

    #[Required]
    public function setUserAddressesUtil(UserAddressesUtil $userAddressesUtil): void
    {
        $this->userAddressesUtil = $userAddressesUtil;
    }

    #[Required]
    public function setUserContext(UserContext $userContext): void
    {
        $this->userContext = $userContext;
    }
}
