<?php

namespace Drupal\api_monitor_client;

use Drupal\Core\Site\Settings;
use Drupal\Core\State\StateInterface;
use Psr\Log\LoggerInterface;

/**
 * Class for API authentication.
 */
class ApiAuthCredentials implements ApiAuthInterface {

  /**
   * Constructor ApiAuthCredentials.
   *
   * @param StateInterface $state
   *   The state instance.
   * @param LoggerInterface $logger
   *   The logger instance.
   */
  public function __construct(
    private readonly StateInterface $state,
    private readonly LoggerInterface $logger,
  ) {}

  /**
   * Executes the call to decrypt data.
   *
   * @return array|null
   *   The decrypted data as an array, or null if decryption fails.
   */
  public function call(): ?array {
    return $this->decrypt();
  }

  /**
   * Decrypts stored client authentication data.
   *
   * This method retrieves encrypted client authentication information, decrypts
   * it using the AES-256-CBC encryption algorithm, and returns the resulting
   * data as an associative array.
   *
   * @return array|null
   *   An associative array of decrypted client authentication data, or NULL
   *   if an error occurs during the decryption process.
   */
  protected function decrypt(): ?array {
    try {
      $master_key_local = Settings::get('api_monitor_vault_key');
      $vault_value = $this->state->get('api_monitor_client_auth');

      $combined = base64_decode($vault_value);
      $iv_length = openssl_cipher_iv_length('aes-256-cbc');
      $iv = substr($combined, 0, $iv_length);
      $encrypted_raw = substr($combined, $iv_length);

      $decrypted_json = openssl_decrypt($encrypted_raw, 'aes-256-cbc', $master_key_local, 0, $iv);
      return json_decode($decrypted_json, TRUE);
    }
    catch (\Exception $e) {
      $this->logger->error($e->getMessage());
      return NULL;
    }
  }

}
