<?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\Configuration\Message\Factory;

use InPost\International\Configuration\DTO\GeocoderConfigInterface;
use InPost\International\Configuration\DTO\GoogleMapsGeocoderConfig;
use InPost\International\Configuration\Message\UpdateCheckoutConfigurationCommand;
use InPost\International\Configuration\Repository\CheckoutConfigurationRepositoryInterface;
use InPost\International\Configuration\Repository\GeocodingConfigurationRepositoryInterface;

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

class UpdateCheckoutConfigurationCommandFactory
{
    private const GEOCODER_OPTIONS_CLASSES = [
        GoogleMapsGeocoderConfig::class,
    ];

    /**
     * @var CheckoutConfigurationRepositoryInterface
     */
    private $checkoutConfigRepository;

    /**
     * @var GeocodingConfigurationRepositoryInterface
     */
    private $geocodingConfigRepository;

    /**
     * @var class-string<GeocoderConfigInterface>[]
     */
    private $geocoderConfigClassNames;

    /**
     * @param class-string<GeocoderConfigInterface>[] $geocoderConfigClassNames
     */
    public function __construct(CheckoutConfigurationRepositoryInterface $checkoutConfigRepository, GeocodingConfigurationRepositoryInterface $geocodingConfigRepository, array $geocoderConfigClassNames = self::GEOCODER_OPTIONS_CLASSES)
    {
        $this->checkoutConfigRepository = $checkoutConfigRepository;
        $this->geocodingConfigRepository = $geocodingConfigRepository;
        $this->geocoderConfigClassNames = $geocoderConfigClassNames;
    }

    public function createCommand(): UpdateCheckoutConfigurationCommand
    {
        $checkoutConfig = $this->checkoutConfigRepository->getCheckoutConfiguration();

        $command = (new UpdateCheckoutConfigurationCommand())
            ->setClosestPointSerachMode($checkoutConfig->getClosestPointSearchMode());

        foreach ($this->geocoderConfigClassNames as $className) {
            if (null === $config = $this->createGeocoderConfig($className)) {
                continue;
            }

            $command->addGeocoderConfig($config);
        }

        return $command;
    }

    /**
     * @template T of GeocoderConfigInterface
     *
     * @param class-string<T> $className
     *
     * @return T|null
     */
    private function createGeocoderConfig(string $className): ?GeocoderConfigInterface
    {
        $type = $className::getGeocoderTypeId();

        if (null === $options = $this->geocodingConfigRepository->getGeocoderOptions($type)) {
            return null;
        }

        return $className::fromArray($options);
    }
}
