<?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\Common\Collections\Criteria;
use Doctrine\ORM\EntityManagerInterface;
use InPost\International\Entity\PickupAddress;
use InPost\International\PickupAddress\Exception\PickupAddressException;
use InPost\International\PickupAddress\Exception\PickupAddressNotFoundException;
use InPost\International\PickupAddress\Message\DeletePickupAddressCommand;
use InPost\International\PickupAddress\PickupAddressRepositoryInterface;

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

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

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

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

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

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

        if ($address->isDeleted()) {
            throw new PickupAddressException('Pickup address is already deleted.');
        }

        if ($address->isDefault()) {
            $this->selectNewDefaultAddress($addressId);
        }

        if ($address->wasUsed()) {
            $address->delete();
            $this->entityManager->flush();
        } else {
            $this->repository->remove($address);
        }
    }

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

    private function selectNewDefaultAddress(int $currentId): void
    {
        $criteria = Criteria::create()
            ->where(Criteria::expr()->eq('deleted', false))
            ->andWhere(Criteria::expr()->neq('id', $currentId))
            ->orderBy(['id' => 'DESC'])
            ->setMaxResults(1);

        /** @var PickupAddress|false $address */
        $address = $this->repository->matching($criteria)->first();

        if (false === $address) {
            return;
        }

        $address->setDefault(true);
    }
}
