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

use Paysera\CheckoutSdk\Entity\PaymentApiCredentials;

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

class CredentialsValidator
{
    public const ERROR_CLIENT_ID_EMPTY = 'client_id_empty';
    public const ERROR_CLIENT_SECRET_EMPTY = 'client_secret_empty';

    /**
     * @var array<string, string>
     */
    private array $errors;

    public function __construct()
    {
        $this->errors = [];
    }

    public function validate(PaymentApiCredentials $credentials): bool
    {
        $this->errors = [];

        $this->validateClientId($credentials->getClientId());
        $this->validateClientSecret($credentials->getClientSecret());

        return count($this->errors) === 0;
    }

    /**
     * @return array<string, string>
     */
    public function getErrors(): array
    {
        return $this->errors;
    }

    public function getFirstError(): ?string
    {
        return count($this->errors) > 0 ? reset($this->errors) : null;
    }

    private function validateClientId(string $clientId): void
    {
        if (trim($clientId) === '') {
            $this->addError('client_id', self::ERROR_CLIENT_ID_EMPTY);
        }
    }

    private function validateClientSecret(string $clientSecret): void
    {
        if (trim($clientSecret) === '') {
            $this->addError('client_secret', self::ERROR_CLIENT_SECRET_EMPTY);
        }
    }

    private function addError(string $field, string $errorCode): void
    {
        $this->errors[$field] = $errorCode;
    }
}
