<?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\CreateShopDeliveryCarrierCommand;
use Gls\GlsPoland\PrestaShop\ObjectModel\Repository\CarrierRepository;

final class CreateShopDeliveryCarrierHandler implements CreateShopDeliveryCarrierHandlerInterface
{
    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(CreateShopDeliveryCarrierCommand $command): CarrierId
    {
        $prestaShopCarrier = $this->factory->create($command);
        $this->carrierRepository->add($prestaShopCarrier);
        $carrierId = CarrierId::from((int) $prestaShopCarrier->getCarrier()->id);

        $this->connection->insert($this->dbPrefix . 'gls_poland_carrier', [
            'id_reference' => $carrierId->getValue(),
            'type' => (string) $command->getType(),
            'countries' => implode(',', $command->getCountryIsoCodes()),
            'parcelshop_type' => null !== $command->getParcelShopType() ? $command->getParcelShopType()->getValue() : null,
            'cash_on_delivery' => null,
            'saturday_delivery' => null,
            'delivery_before_10' => null,
            'delivery_before_12' => null,
            'document_return' => null,
        ]);

        return $carrierId;
    }
}
