<?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\ORM\EntityManagerInterface;
use InPost\International\ParcelTemplate\Exception\ParcelTemplateNotFoundException;
use InPost\International\ParcelTemplate\Message\SelectDefaultParcelTemplateCommand;
use InPost\International\ParcelTemplate\ParcelTemplateRepositoryInterface;

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

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

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

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

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

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

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

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

        $template->setDefault(true);

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

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