<?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\ParcelTemplate\MessageHandler;

use Doctrine\Common\Collections\Criteria;
use InPost\International\Entity\ParcelTemplate;
use InPost\International\ParcelTemplate\Exception\ParcelTemplateNotFoundException;
use InPost\International\ParcelTemplate\Message\DeleteParcelTemplateCommand;
use InPost\International\ParcelTemplate\ParcelTemplateRepositoryInterface;

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

final class DeleteParcelTemplateHandler
{
    /**
     * @var ParcelTemplateRepositoryInterface
     */
    private $repository;

    public function __construct(ParcelTemplateRepositoryInterface $repository)
    {
        $this->repository = $repository;
    }

    public function __invoke(DeleteParcelTemplateCommand $command): void
    {
        $templateId = $command->getTemplateId();

        if (null === $template = $this->repository->find($templateId)) {
            throw new ParcelTemplateNotFoundException('Parcel template does not exist.');
        }

        if ($template->isDefault()) {
            $this->selectNewDefaultAddress($templateId);
        }

        $this->repository->remove($template);
    }

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

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

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

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

        $template->setDefault(true);
    }
}
