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

use InPost\International\Carrier\CarrierRepositoryInterface;
use InPost\International\Carrier\Exception\CarrierNotFoundException;
use InPost\International\Carrier\Message\DeleteCarrierCommand;
use InPost\International\PrestaShop\ObjectModel\Repository\CarrierRepository as ObjectModelRepository;
use InPost\International\PrestaShop\ObjectModel\Repository\ObjectRepositoryInterface;

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

final class DeleteCarrierHandler
{
    /**
     * @var CarrierRepositoryInterface
     */
    private $repository;

    /**
     * @var ObjectModelRepository
     */
    private $objectModelRepository;

    /**
     * @param ObjectModelRepository $objectModelRepository
     */
    public function __construct(CarrierRepositoryInterface $repository, ObjectRepositoryInterface $objectModelRepository)
    {
        $this->repository = $repository;
        $this->objectModelRepository = $objectModelRepository;
    }

    public function __invoke(DeleteCarrierCommand $command): void
    {
        $carrierId = $command->getCarrierId();

        if (null === $carrier = $this->repository->find($carrierId)) {
            throw new CarrierNotFoundException('Carrier does not exist.');
        }

        $this->deleteObjectModel($carrierId);
        $this->repository->remove($carrier);
    }

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

    private function deleteObjectModel(int $referenceId): void
    {
        $carrier = $this->objectModelRepository->findOneByReferenceId($referenceId);

        if (null === $carrier || $carrier->deleted) {
            return;
        }

        $this->objectModelRepository->remove($carrier);
    }
}
