<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\MessageHandler\Carrier;

use Doctrine\ORM\EntityManagerInterface;
use Gls\GlsPoland\Carrier\CarrierId;
use Gls\GlsPoland\Country\IsoCode;
use Gls\GlsPoland\Entity\CourierCarrier;
use Gls\GlsPoland\PrestaShop\Message\CreateCourierCarrierCommand;
use Gls\GlsPoland\PrestaShop\ObjectModel\Repository\CarrierRepository;

final class CreateCourierCarrierHandler implements CreateCourierCarrierHandlerInterface
{
    private $entityManager;
    private $factory;
    private $carrierRepository;

    public function __construct(EntityManagerInterface $entityManager, CarrierFactoryInterface $factory, CarrierRepository $carrierRepository)
    {
        $this->entityManager = $entityManager;
        $this->factory = $factory;
        $this->carrierRepository = $carrierRepository;
    }

    public function handle(CreateCourierCarrierCommand $command): CarrierId
    {
        $countries = array_map([IsoCode::class, 'from'], $command->getCountryIsoCodes());

        $prestaShopCarrier = $this->factory->create($command);
        $this->carrierRepository->add($prestaShopCarrier);
        $carrierId = CarrierId::from((int) $prestaShopCarrier->getCarrier()->id);

        $services = $command->getServices();

        $carrier = new CourierCarrier(
            $carrierId,
            $countries,
            $services->isCashOnDelivery(),
            $services->isSaturdayDelivery(),
            $services->isDeliveryBefore10(),
            $services->isDeliveryBefore12(),
            $services->isDocumentReturn()
        );

        $this->entityManager->persist($carrier);
        $this->entityManager->flush();

        return $carrierId;
    }
}
