<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\MessageHandler\Carrier;

use Doctrine\DBAL\Connection;
use Gls\GlsPoland\Carrier\CarrierId;
use Gls\GlsPoland\PrestaShop\Message\CreateCourierCarrierCommand;
use Gls\GlsPoland\PrestaShop\ObjectModel\Repository\CarrierRepository;

final class CreateCourierCarrierHandler implements CreateCourierCarrierHandlerInterface
{
    private $connection;
    private $factory;
    private $carrierRepository;
    private $dbPrefix;

    public function __construct(Connection $connection, CarrierFactoryInterface $factory, CarrierRepository $carrierRepository, string $dbPrefix)
    {
        $this->connection = $connection;
        $this->factory = $factory;
        $this->carrierRepository = $carrierRepository;
        $this->dbPrefix = $dbPrefix;
    }

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

        $services = $command->getServices();

        $this->connection->insert($this->dbPrefix . 'gls_poland_carrier', [
            'id_reference' => $carrierId->getValue(),
            'type' => (string) $command->getType(),
            'countries' => implode(',', $command->getCountryIsoCodes()),
            'cash_on_delivery' => (int) $services->isCashOnDelivery(),
            'saturday_delivery' => (int) $services->isSaturdayDelivery(),
            'delivery_before_10' => (int) $services->isDeliveryBefore10(),
            'delivery_before_12' => (int) $services->isDeliveryBefore12(),
            'document_return' => (int) $services->isDocumentReturn(),
        ]);

        return $carrierId;
    }
}
