<?php
/**
 * 2026 Paysera
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2026 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of Paysera
 */

declare(strict_types=1);

namespace Paysera\PrestashopPayments\Provider;

use Evp\Component\Money\Money;
use Paysera\CheckoutSdk\Entity\PaymentCountry;
use Paysera\CheckoutSdk\Entity\PaymentMethod;
use Paysera\CheckoutSdk\Entity\PaymentMethodFilter;
use Paysera\CheckoutSdk\SdkFacade;
use Psr\Log\LoggerInterface;

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

class PaymentMethodProvider implements PaymentMethodProviderInterface
{
    private SdkFacade $sdkFacade;
    private LoggerInterface $logger;

    public function __construct(
        SdkFacade $sdkFacade,
        LoggerInterface $logger
    ) {
        $this->sdkFacade = $sdkFacade;
        $this->logger = $logger;
    }

    public function getPaymentMethodsForCountry(string $countryCode, Money $amount = null): array
    {
        try {
            $filter = $this->createFilter($amount);
            $paymentMethods = $this->sdkFacade
                ->getPaymentsFacade()
                ->getPaymentMethods($filter)
            ;
            $methods = $this->filterMethodsByCountry($paymentMethods, $countryCode);

            $this->logger->debug('Fetched payment methods for country', [
                'country' => $countryCode,
                'count' => count($methods),
            ]);

            return $methods;
        } catch (\Throwable $exception) {
            $this->logger->error('Failed to fetch payment methods for country', [
                'country' => $countryCode,
                'error' => $exception->getMessage(),
                'code' => $exception->getCode(),
            ]);

            return [];
        }
    }

    private function createFilter(?Money $amount): ?PaymentMethodFilter
    {
        if ($amount === null) {
            return null;
        }

        $amountInMinorUnits = $amount->getAmountInMinorUnits();

        if ($amountInMinorUnits === null) {
            return null;
        }

        return new PaymentMethodFilter(
            $amountInMinorUnits,
            $amount->getCurrency()
        );
    }

    private function filterMethodsByCountry(iterable $paymentMethods, string $countryCode): array
    {
        $methods = [];

        foreach ($paymentMethods as $method) {
            if (
                $countryCode === PaymentCountry::ALL_COUNTRIES_CODE
                || $this->isMethodAvailableForCountry($method, $countryCode)
            ) {
                $methods[] = $this->formatMethod($method);
            }
        }

        return $methods;
    }

    private function isMethodAvailableForCountry(PaymentMethod $method, string $countryCode): bool
    {
        $availableCountries = $method->getAvailableCountries();

        if ($availableCountries->count() === 0) {
            return true;
        }

        foreach ($availableCountries as $country) {
            if ($country->getCode() === $countryCode) {
                return true;
            }
        }

        return false;
    }

    private function formatMethod(PaymentMethod $method): array
    {
        $iconUrl = $method->getIconUrl();

        return [
            'key' => $method->getKey(),
            'title' => $method->getTitle(),
            'description' => $method->getDescription(),
            'logo_url' => $iconUrl !== '' ? $iconUrl : null,
        ];
    }
}
