<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\MessageHandler\Carrier;

use Gls\GlsPoland\PrestaShop\Message\DeleteCarrierCommand;
use Gls\GlsPoland\PrestaShop\ObjectModel\Repository\CarrierRepository as ObjectModelRepository;
use Gls\GlsPoland\Repository\CarrierRepository;

final class DeleteCarrierHandler implements DeleteCarrierHandlerInterface
{
    private $entityRepository;
    private $objectModelRepository;

    public function __construct(CarrierRepository $entityRepository, ObjectModelRepository $objectModelRepository)
    {
        $this->entityRepository = $entityRepository;
        $this->objectModelRepository = $objectModelRepository;
    }

    public function handle(DeleteCarrierCommand $command): void
    {
        if (null === $entity = $this->entityRepository->find($command->getCarrierId())) {
            return;
        }

        $this->deleteObjectModel($entity->getId()->getValue());
        $this->entityRepository->remove($entity);
    }

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

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

        if ($carrier->isUsed()) {
            $carrier->deleted = true;
            $carrier->setFieldsToUpdate(['deleted' => true]);
            $this->objectModelRepository->update($carrier);
        } else {
            $this->objectModelRepository->remove($carrier);
        }
    }
}
