<?php

declare(strict_types=1);

namespace Drupal\ai\Plugin\AiPlatform;

use Drupal\Component\Plugin\DependentPluginInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\PluginDependencyTrait;
use Drupal\key\KeyRepositoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Base class for AI platforms that use API key auth via the Key module.
 */
abstract class AiPlatformUsingApiKeyAuthenticationPluginBase extends AiPlatformPluginBase implements AiPlatformInterface, DependentPluginInterface {

  use PluginDependencyTrait;

  /**
   * The key repository.
   *
   * @var \Drupal\key\KeyRepositoryInterface|null
   */
  protected KeyRepositoryInterface|null $keyRepository = NULL;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $instance->keyRepository = $container->get('key.repository');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration(): array {
    return parent::defaultConfiguration() + [
      'key_id' => NULL,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state): array {
    $form['key_id'] = [
      '#type' => 'key_select',
      '#title' => $this->t('@platform API Key', ['@platform' => $this->label()]),
      '#description' => $this->t('The @platform API key.', ['@platform' => $this->label()]),
      '#default_value' => $this->getConfiguration()['key_id'],
      '#required' => TRUE,
    ];

    return $form;
  }

  /**
   * Gets the API key value from the configured key entity.
   *
   * @return string|null
   *   The API key value or NULL if not found.
   */
  protected function getApiKey(): ?string {
    $key_id = $this->getConfiguration()['key_id'];
    if (empty($key_id)) {
      return NULL;
    }
    return $this->keyRepository->getKey($key_id)?->getKeyValue();
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies(): array {
    $key_id = $this->getConfiguration()['key_id'];
    if (!empty($key_id)) {
      if ($key = $this->keyRepository->getKey($key_id)) {
        $this->addDependency('config', $key->getConfigDependencyName());
      }
    }

    return $this->dependencies;
  }

}
