<?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 Psr\Cache\CacheItemPoolInterface;

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

class CachedPaymentMethodProvider implements PaymentMethodProviderInterface
{
    private const CACHE_TTL_SECONDS = 300;
    private const CACHE_KEY_PREFIX = 'payment_methods_';

    private PaymentMethodProviderInterface $provider;
    private CacheItemPoolInterface $cache;

    public function __construct(PaymentMethodProviderInterface $provider, CacheItemPoolInterface $cache)
    {
        $this->provider = $provider;
        $this->cache = $cache;
    }

    public function getPaymentMethodsForCountry(string $countryCode, Money $amount = null): array
    {
        $cacheKey = $this->buildCacheKey($countryCode, $amount);
        $item = $this->cache->getItem($cacheKey);

        if ($item->isHit()) {
            return $item->get();
        }

        $methods = $this->provider->getPaymentMethodsForCountry($countryCode, $amount);

        if ($methods !== []) {
            $item->set($methods);
            $item->expiresAfter(self::CACHE_TTL_SECONDS);
            $this->cache->save($item);
        }

        return $methods;
    }

    private function buildCacheKey(string $countryCode, ?Money $amount): string
    {
        if ($amount === null) {
            return self::CACHE_KEY_PREFIX . $countryCode;
        }

        $amountInMinorUnits = $amount->getAmountInMinorUnits();

        if ($amountInMinorUnits === null) {
            return self::CACHE_KEY_PREFIX . $countryCode;
        }

        return self::CACHE_KEY_PREFIX . $countryCode . '_' . $amountInMinorUnits . '_' . $amount->getCurrency();
    }
}
