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

use Paysera\CheckoutSdk\Entity\Collection\PaymentMethodCollection;
use Paysera\CheckoutSdk\SdkFacade;
use Paysera\PrestashopPayments\Dto\PayseraPaymentMethod;
use Paysera\PrestashopPayments\Repository\PayseraPaymentMethodRepository;
use Psr\Log\LoggerInterface;

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

class PaymentMethodTitleResolver
{
    public function __construct(
        private SdkFacade $sdkFacade,
        private PayseraPaymentMethodRepository $repository,
        private LoggerInterface $logger
    ) {
    }

    public function resolve(string $key): PayseraPaymentMethod
    {
        if ($key === '') {
            return new PayseraPaymentMethod('', '');
        }

        $stored = $this->repository->findByKey($key);
        if ($stored !== null) {
            return $stored;
        }

        $catalogue = $this->fetchCatalogue();
        if ($catalogue === null) {
            return new PayseraPaymentMethod($key, $key);
        }

        $resolvedTitle = null;

        foreach ($catalogue as $method) {
            $methodKey = $method->getKey();
            $methodTitle = $method->getTitle();

            if ($methodKey === '' || $methodTitle === '') {
                continue;
            }

            $this->repository->save(new PayseraPaymentMethod($methodKey, $methodTitle));

            if ($methodKey === $key) {
                $resolvedTitle = $methodTitle;
            }
        }

        if ($resolvedTitle === null) {
            $fallback = new PayseraPaymentMethod($key, $key);
            $this->repository->save($fallback);

            return $fallback;
        }

        return new PayseraPaymentMethod($key, $resolvedTitle);
    }

    /**
     * @return PaymentMethodCollection<\Paysera\CheckoutSdk\Entity\PaymentMethod>|null
     */
    private function fetchCatalogue(): ?PaymentMethodCollection
    {
        try {
            return $this->sdkFacade->getPaymentsFacade()->getPaymentMethods();
        } catch (\Throwable $exception) {
            $this->logger->error('Failed to fetch payment methods catalogue', [
                'error' => $exception->getMessage(),
            ]);

            return null;
        }
    }
}
