<?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\PaymentApiCredentials;
use Paysera\CheckoutSdk\Exception\IntegrationException;
use Paysera\CheckoutSdk\SdkFacade;
use Paysera\PrestashopPayments\Repository\ApiAuthTokenRepositoryInterface;
use Paysera\PrestashopPayments\Repository\ApiCredentialsRepositoryInterface;
use Psr\Log\LoggerInterface;

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

class AuthorizationService
{
    private SdkFacade $sdkFacade;
    private ApiCredentialsRepositoryInterface $credentialsRepository;
    private ApiAuthTokenRepositoryInterface $tokenRepository;
    private LoggerInterface $logger;

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

    public function isValidCredentials(PaymentApiCredentials $credentials): bool
    {
        return $this->authorizeWithCredentials($credentials);
    }

    public function authorize(string $clientId, string $clientSecret): bool
    {
        $credentials = new PaymentApiCredentials($clientId, $clientSecret);

        return $this->authorizeWithCredentials($credentials);
    }

    private function authorizeWithCredentials(PaymentApiCredentials $credentials): bool
    {
        try {
            $this->logger->debug('Attempting authorization');

            $token = $this->sdkFacade
                ->getAuthorizationFacade()
                ->authorize($credentials)
            ;

            return true;
        } catch (IntegrationException $exception) {
            $this->logger->error('Authorization failed', [
                'exception' => $exception->getMessage(),
                'exception_code' => $exception->getCode(),
                'previous_exception' => $exception->getPrevious() !== null ? $exception->getPrevious()->getMessage() : null,
            ]);

            $this->credentialsRepository->delete();
            $this->tokenRepository->delete();

            return false;
        }
    }

    public function isAuthorized(): bool
    {
        return $this->getStoredCredentials() !== null;
    }

    public function getStoredCredentials(): ?PaymentApiCredentials
    {
        try {
            return $this->sdkFacade
                ->getAuthorizationFacade()
                ->getStoredPaymentApiCredentials()
            ;
        } catch (IntegrationException) {
            return null;
        }
    }
}
