<?php

namespace KupShop\UserManagerBundle\EventListener;

use KupShop\KupShopBundle\Context\UserContext;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\KupShopBundle\Util\Mail\EmailCheck;
use KupShop\OrderingBundle\Event\CartEvent;
use Query\Operator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class CartListener implements EventSubscriberInterface
{
    public function __construct(private EmailCheck $emailCheck)
    {
    }

    public static function getSubscribedEvents()
    {
        return [
            CartEvent::CHECK_CART_ITEMS => [
                ['checkUserAddresses', 200],
            ],
        ];
    }

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

        if (!($userId = (int) $cart->getData('userManager-user'))) {
            $userId = (int) Contexts::get(UserContext::class)->getActiveId();
        }

        if (!($user = \User::createFromId($userId))) {
            return;
        }

        $emailIsValid = true;
        if ($cart->invoice['email'] === $user->email) {
            $emailIsValid = $this->emailCheck->isEmailDomainValid($user->email);
        }

        if ($emailIsValid && ((int) $cart->getData('userManager-addressesSet') === $userId)) {
            return;
        }

        $user->fetchAddresses();

        if (!$this->emailCheck->isEmailDomainValid($user->email)) {
            $masterEmail = sqlQueryBuilder()
                ->select('u.email')
                ->from('users_manager_relations', 'umr')
                ->join('umr', 'users', 'u', 'u.id = umr.id_user_master')
                ->where(Operator::equals(['umr.id_user' => $user->id]))
                ->execute()->fetchOne();

            $user->email = $masterEmail;
            $user->invoice['email'] = $masterEmail;
        }

        $cart->invoice = $user->invoice;
        $cart->delivery = $user->delivery;
        $cart->addressesSet = true;

        $cart->setData('userManager-addressesSet', $userId);
        $cart->save();
    }
}
