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

use Paysera\CheckoutSdk\Entity\PaymentApiCredentials;
use Paysera\CheckoutSdk\Repository\PaymentApiCredentialsRepositoryInterface;
use Paysera\PrestashopPayments\Service\AuthorizationService;
use Paysera\PrestashopPayments\Validator\CredentialsValidator;
use PrestaShop\PrestaShop\Core\Configuration\DataConfigurationInterface;
use Psr\Log\LoggerInterface;

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

final class AuthorizationDataConfiguration implements DataConfigurationInterface
{
    private AuthorizationService $authorizationService;
    private CredentialsValidator $credentialsValidator;
    private PaymentApiCredentialsRepositoryInterface $credentialsRepository;
    private LoggerInterface $logger;

    public function __construct(
        AuthorizationService $authorizationService,
        CredentialsValidator $credentialsValidator,
        PaymentApiCredentialsRepositoryInterface $credentialsRepository,
        LoggerInterface $logger
    ) {
        $this->authorizationService = $authorizationService;
        $this->credentialsValidator = $credentialsValidator;
        $this->credentialsRepository = $credentialsRepository;
        $this->logger = $logger;
    }

    /**
     * @return array{client_id: string, client_secret: string}
     */
    public function getConfiguration(): array
    {
        $credentials = $this->credentialsRepository->retrieve();

        if ($credentials === null) {
            return [
                'client_id' => '',
                'client_secret' => '',
            ];
        }

        return [
            'client_id' => $credentials->getClientId(),
            'client_secret' => $credentials->getClientSecret(),
        ];
    }

    /**
     * @param array{client_id: string, client_secret: string} $configuration
     *
     * @return list<string>
     */
    public function updateConfiguration(array $configuration): array
    {
        $errors = [];

        $this->logger->debug('Updating authorization configuration');

        if ($this->validateConfiguration($configuration)) {
            $clientId = trim($configuration['client_id']);
            $clientSecret = trim($configuration['client_secret']);
            $credentials = new PaymentApiCredentials($clientId, $clientSecret);
            $this->credentialsRepository->save($credentials);

            $this->logger->info('Authorization credentials saved successfully', [
                'client_id' => $clientId,
            ]);
        } else {
            $errorMessage = $this->getValidationError();
            $errors[] = $errorMessage;

            $this->logger->warning('Authorization credentials validation failed', [
                'error' => $errorMessage,
            ]);
        }

        return $errors;
    }

    /**
     * @param array<string, string> $configuration
     */
    public function validateConfiguration(array $configuration): bool
    {
        if (!isset($configuration['client_id'], $configuration['client_secret'])) {
            return false;
        }

        $clientId = trim($configuration['client_id']);
        $clientSecret = trim($configuration['client_secret']);

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

        $credentials = new PaymentApiCredentials($clientId, $clientSecret);

        if (!$this->credentialsValidator->validate($credentials)) {
            return false;
        }

        return $this->authorizationService->isValidCredentials($credentials);
    }

    private function getValidationError(): string
    {
        $errorCode = $this->credentialsValidator->getFirstError();

        if ($errorCode !== null) {
            return $errorCode;
        }

        return 'Invalid Client ID or Client Secret. Please check your credentials and try again.';
    }
}
