<?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\CarrierConfiguration;
use InPost\International\Carrier\CarrierRepositoryInterface;
use InPost\International\Carrier\CarrierType;
use InPost\International\Carrier\Configurator\CarrierConfiguratorInterface;
use InPost\International\Carrier\Exception\CarrierException;
use InPost\International\Carrier\Message\CreateCarrierCommand;
use InPost\International\Entity\Carrier;
use InPost\International\Entity\CourierCarrier;
use InPost\International\Entity\PointDeliveryCarrier;
use InPost\International\PrestaShop\ObjectModel\Repository\CarrierRepository as ObjectModelRepository;
use InPost\International\PrestaShop\ObjectModel\Repository\ObjectRepositoryInterface;
use Symfony\Component\Filesystem\Filesystem;

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

final class CreateCarrierHandler
{
    /**
     * @var CarrierConfiguratorInterface
     */
    private $configurator;

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

    /**
     * @var CarrierRepositoryInterface
     */
    private $repository;

    /**
     * @var Filesystem
     */
    private $filesystem;

    /**
     * @var string
     */
    private $imageDir;

    /**
     * @param ObjectModelRepository $objectModelRepository
     */
    public function __construct(CarrierConfiguratorInterface $configurator, ObjectRepositoryInterface $objectModelRepository, CarrierRepositoryInterface $repository, Filesystem $filesystem, string $imageDir = _PS_SHIP_IMG_DIR_)
    {
        $this->configurator = $configurator;
        $this->objectModelRepository = $objectModelRepository;
        $this->repository = $repository;
        $this->filesystem = $filesystem;
        $this->imageDir = rtrim($imageDir, '/');
    }

    public function __invoke(CreateCarrierCommand $command): Carrier
    {
        if (null === $command->getType()) {
            throw new CarrierException('Carrier type is not specified.');
        }

        if ([] === $command->getCountries()) {
            throw new CarrierException('Carrier has to be available in at least a single country.');
        }

        $configuration = $this->createConfiguration($command);
        $this->objectModelRepository->add($configuration);

        try {
            $carrier = $this->createCarrier($configuration->getCarrier(), $command);
            $this->repository->add($carrier);
        } catch (\Throwable $e) {
            try {
                $this->objectModelRepository->remove($configuration->getCarrier());
            } finally {
                throw $e;
            }
        }

        $this->copyLogo($configuration);

        return $carrier;
    }

    public function handle(CreateCarrierCommand $command): Carrier
    {
        return ($this)($command);
    }

    private function createConfiguration(CreateCarrierCommand $command): CarrierConfiguration
    {
        $configuration = new CarrierConfiguration(new \Carrier());
        $this->configurator->configure($configuration, $command);

        return $configuration;
    }

    private function createCarrier(\Carrier $carrier, CreateCarrierCommand $command): Carrier
    {
        if (CarrierType::PointDelivery() === $command->getType()) {
            return new PointDeliveryCarrier($carrier, ...$command->getCountries());
        }

        return new CourierCarrier($carrier, ...$command->getCountries());
    }

    private function copyLogo(CarrierConfiguration $configuration): void
    {
        if (null === $path = $configuration->getLogoPath()) {
            return;
        }

        $targetFileName = sprintf('%s/%d.jpg', $this->imageDir, $configuration->getCarrier()->id);
        $this->filesystem->copy($path, $targetFileName);
    }
}
