<?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\Installer;

use InPost\International\Api\Shipment\Model\Service\Currency;
use InPost\International\Installer\Exception\InstallerException;
use PrestaShop\PrestaShop\Core\Localization\Exception\LocalizationException;
use PrestaShop\PrestaShop\Core\Localization\Locale;
use PrestaShop\PrestaShop\Core\Localization\LocaleInterface;
use PrestaShop\PrestaShop\Core\Localization\Pack\Import\LocalizationPackImportConfig;
use PrestaShop\PrestaShop\Core\Localization\Pack\Import\LocalizationPackImportConfigInterface;
use PrestaShop\PrestaShop\Core\Localization\Pack\Import\LocalizationPackImporterInterface;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Contracts\Translation\TranslatorInterface;

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

/**
 * On PS 8 and later, one of the {@see MoneyType} form extensions throws if the currency does not exist in the database.
 *
 * @see \PrestaShopBundle\Form\Admin\Type\CustomMoneyType::getFrameworkPattern()
 */
final class CurrencyInstaller implements InstallerInterface
{
    /**
     * @var Locale
     */
    private $locale;

    /**
     * @var LocalizationPackImporterInterface
     */
    private $importer;

    /**
     * @var TranslatorInterface
     */
    private $translator;

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

    /**
     * @param Locale $locale
     */
    public function __construct(LocaleInterface $locale, LocalizationPackImporterInterface $importer, TranslatorInterface $translator, string $psVersion = _PS_VERSION_)
    {
        $this->locale = $locale;
        $this->importer = $importer;
        $this->translator = $translator;
        $this->psVersion = $psVersion;
    }

    public function install(\Module $module): void
    {
        if (\Tools::version_compare($this->psVersion, '8.0.0')) {
            return;
        }

        $currency = Currency::Euro();
        $isoCode = $currency->value;

        try {
            $this->locale->getPriceSpecification($isoCode);

            return;
        } catch (LocalizationException $e) {
            // currency does not exist in the database
        }

        $country = current($currency->getCountries());

        try {
            $errors = $this->importer->import(new LocalizationPackImportConfig(
                strtolower($country->value),
                [LocalizationPackImportConfigInterface::CONTENT_CURRENCIES],
                true
            ));

            if ([] === $errors) {
                return;
            }

            $message = $this->translator->trans('Could not import currency "{isoCode}": {errors}', [
                '{isoCode}' => $isoCode,
                '{errors}' => implode("\n", array_map('strval', $errors)),
            ], 'Modules.Inpostinternational.Installer');

            throw new InstallerException($message);
        } catch (\Exception $e) {
            throw new InstallerException($this->translator->trans('Could not import currency "{isoCode}".', ['{isoCode}' => $isoCode], 'Modules.Inpostinternational.Installer'), 0, $e);
        }
    }
}
