<?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\PaymentApiCredentials;
use Paysera\PrestashopPayments\Enum\ConfigurationKey;
use Psr\Log\LoggerInterface;

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

class ApiCredentialsRepository implements ApiCredentialsRepositoryInterface
{
    private LoggerInterface $logger;

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

    public function save(PaymentApiCredentials $apiCredentials): void
    {
        $this->logger->info('Persisting payment API credentials');

        \Configuration::updateValue(
            ConfigurationKey::CLIENT_ID,
            $apiCredentials->getClientId()
        );
        \Configuration::updateValue(
            ConfigurationKey::CLIENT_SECRET,
            $apiCredentials->getClientSecret()
        );
    }

    public function retrieve(): ?PaymentApiCredentials
    {
        $this->logger->debug('Retrieving payment API credentials');

        $clientId = \Configuration::get(ConfigurationKey::CLIENT_ID);
        $clientSecret = \Configuration::get(ConfigurationKey::CLIENT_SECRET);

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

        return new PaymentApiCredentials($clientId, $clientSecret);
    }

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

        \Configuration::deleteByName(ConfigurationKey::CLIENT_ID);
        \Configuration::deleteByName(ConfigurationKey::CLIENT_SECRET);
    }
}
