<?php declare(strict_types=1);

namespace Shop\Application\Client\ClientUpdate;

use Shop\Application\Office\CustomerRegistration\CustomerRegistrationException;
use Shop\Application\Office\CustomerRegistration\CustomerRequest;
use Shop\Application\Office\OfficeService;
use Shop\Infrastructure\Repositories\City\CityCriteria;
use Shop\Infrastructure\Repositories\City\CityRepository;
use Shop\Infrastructure\Repositories\Customer\CustomerCriteria;
use Shop\Presentation\Config\MainConfig;

class ClientUpdateHandler
{


    public function __construct(protected OfficeService  $officeService,
                                protected CityRepository $cityRepository,
                                protected MainConfig     $mainConfig)
    {
    }

    public function handle(ClientUpdateCommand $command): void
    {

        $email = trim($command->getEmail());
        $name = trim($command->getFullName());
        $phone = trim($command->getPhone());
        $cityName = trim($command->getCityName());

        $city = $this->cityRepository->findByCriteria(CityCriteria::create()->setSearchByName($cityName))->current();


        if ($city) {
            $cityId = $city->getId();
        } else {
            $cityId = (int)$this->mainConfig->getDefaultCity();
        }


        //создаем клиента
        if (!$customer = $command->getCustomer()) {

            $existCustomer = $this->officeService->getCustomerRepository()->findByCriteria(
                CustomerCriteria::create()->setFilterByEmail(trim($email))
            )->current();

            //Создаем пользователя
            if (!$existCustomer) {

                $newCustomer = new CustomerRequest();
                $newCustomer
                    ->setName($name)
                    ->setEmail($email)
                    ->setPhone($phone)
                    ->setCityId($cityId)
                    ->setgroupId($this->mainConfig->getDefaultCustomerGroup());

                try {
                    $customer = $this->officeService->registerCustomer($newCustomer);
                }
                catch (CustomerRegistrationException $ex){
                    throw new ClientUpdateException($ex->getMessage());
                }


            } else {
                //Меняем даненые у пользователя
                $customer = $existCustomer;
            }

            $command->setCustomer($customer);
        }

        $customer
            ->setNotifyType('email')
            ->setName($name)
            ->setEmail($email)
            ->setPhone($phone)
            ->setCityId($cityId);
        $this->officeService->getCustomerRepository()->save($customer);
    }

}