<?php

namespace Resursbank\MerchantApi\Service;

use Context as PrestaContext;
use JsonException;
use ReflectionException;
use Resursbank\Ecom\Config;
use Resursbank\Ecom\Exception\ApiException;
use Resursbank\Ecom\Exception\AuthException;
use Resursbank\Ecom\Exception\CacheException;
use Resursbank\Ecom\Exception\ConfigException;
use Resursbank\Ecom\Exception\CurlException;
use Resursbank\Ecom\Exception\FilesystemException;
use Resursbank\Ecom\Exception\TranslationException;
use Resursbank\Ecom\Exception\Validation\EmptyValueException;
use Resursbank\Ecom\Exception\Validation\IllegalTypeException;
use Resursbank\Ecom\Exception\Validation\IllegalValueException;
use Resursbank\Ecom\Exception\Validation\MissingKeyException;
use Resursbank\Ecom\Exception\ValidationException;
use Resursbank\Ecom\Module\PaymentMethod\Repository;
use Resursbank\Ecom\Module\PaymentMethod\Widget\PartPayment as Widget;
use Throwable;

/**
 * Centralized business logic for part payment widget and associated
 * functionality.
 */
class PartPayment
{
    /**
     * @throws TranslationException
     * @throws ValidationException
     * @throws CurlException
     * @throws IllegalValueException
     * @throws IllegalTypeException
     * @throws Throwable
     * @throws EmptyValueException
     * @throws AuthException
     * @throws MissingKeyException
     * @throws JsonException
     * @throws ConfigException
     * @throws ReflectionException
     * @throws ApiException
     * @throws CacheException
     * @throws FilesystemException
     */
    public static function getWidget(
        PrestaContext $context,
        float $amount = 0.0
    ): Widget {
        $config = FakeContainer::getConfig();
        $link = $context->link->getModuleLink(
            module: 'resursbank',
            controller: 'partpayment',
            params: [
                'amount' => $amount,
                'info_request' => 0
            ]
        );

        return new Widget(
            storeId: Config::getStoreId(),
            paymentMethod: Repository::getById(
                paymentMethodId: $config->getPartPaymentPaymentMethod()
            ),
            months: $config->getPartPaymentAnnuityPeriod(),
            amount: $amount,
            currencySymbol: Config::getCurrencySymbol(),
            currencyFormat: Config::getCurrencyFormat(),
            fetchStartingCostUrl: $link,
            threshold: $config->getPartPaymentThreshold()
        );
    }
}
