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

use Paysera\CheckoutSdk\Entity\PaymentApiAuthToken;
use Paysera\CheckoutSdk\Service\Factory\PaymentApiEnvironmentFactory;
use Paysera\PrestashopPayments\Enum\ConfigurationKey;
use Psr\Log\LoggerInterface;

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

class ApiAuthTokenRepository implements ApiAuthTokenRepositoryInterface
{
    private PaymentApiEnvironmentFactory $environmentFactory;
    private LoggerInterface $logger;

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

    public function save(PaymentApiAuthToken $authToken): void
    {
        $this->logger->info('Persisting payment API auth token');

        \Configuration::updateValue(
            ConfigurationKey::PAYMENT_API_TOKEN,
            $authToken->getAccessToken()
        );

        \Configuration::updateValue(
            ConfigurationKey::PAYMENT_API_ENVIRONMENT,
            $authToken->getEnvironment()->getValue()
        );
    }

    public function retrieve(): ?PaymentApiAuthToken
    {
        $this->logger->debug('Retrieving payment API auth token');

        $accessToken = \Configuration::get(ConfigurationKey::PAYMENT_API_TOKEN);

        if ($accessToken === '' || $accessToken === false) {
            return null;
        }

        $environmentString = \Configuration::get(ConfigurationKey::PAYMENT_API_ENVIRONMENT);

        if ($environmentString === '' || $environmentString === false) {
            return null;
        }

        try {
            $environment = $this->environmentFactory->create($environmentString);
        } catch (\Exception $exception) {
            return null;
        }

        return new PaymentApiAuthToken(
            $environment,
            $accessToken
        );
    }

    public function delete(): void
    {
        $this->logger->info('Deleting payment API auth token');

        \Configuration::deleteByName(ConfigurationKey::PAYMENT_API_TOKEN);
        \Configuration::deleteByName(ConfigurationKey::PAYMENT_API_ENVIRONMENT);
    }
}
