<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\PickupAddress\MessageHandler;

use Doctrine\ORM\EntityManagerInterface;
use InPost\International\PickupAddress\Exception\PickupAddressNotFoundException;
use InPost\International\PickupAddress\Message\SelectDefaultPickupAddressCommand;
use InPost\International\PickupAddress\PickupAddressRepositoryInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class SelectDefaultPickupAddressHandler
{
    /**
     * @var PickupAddressRepositoryInterface
     */
    private $repository;

    /**
     * @var EntityManagerInterface
     */
    private $entityManager;

    public function __construct(PickupAddressRepositoryInterface $repository, EntityManagerInterface $entityManager)
    {
        $this->repository = $repository;
        $this->entityManager = $entityManager;
    }

    public function __invoke(SelectDefaultPickupAddressCommand $command): void
    {
        $addressId = $command->getAddressId();

        if (null === $address = $this->repository->find($addressId)) {
            throw new PickupAddressNotFoundException('Pickup address does not exist.');
        }

        if ($address->isDefault()) {
            return;
        }

        if (null !== $previousDefault = $this->repository->getDefault()) {
            $previousDefault->setDefault(false);
        }

        $address->setDefault(true);

        $this->entityManager->flush();
    }

    public function handle(SelectDefaultPickupAddressCommand $command): void
    {
        ($this)($command);
    }
}
