<?php

namespace Drupal\nodehive_api_key_management\Form;

use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\nodehive_api_key_management\Service\ApiKeyManager;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Form for revoking an API key.
 */
class ApiKeyRevokeForm extends ConfirmFormBase {

  /**
   * The API key manager service.
   *
   * @var \Drupal\nodehive_api_key_management\Service\ApiKeyManager
   */
  protected $apiKeyManager;

  /**
   * The key ID.
   *
   * @var int
   */
  protected $keyId;

  /**
   * The key record.
   *
   * @var object
   */
  protected $key;

  /**
   * Constructs an ApiKeyRevokeForm object.
   */
  public function __construct(ApiKeyManager $api_key_manager) {
    $this->apiKeyManager = $api_key_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('nodehive_api_key_management.api_key_manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'nodehive_api_key_revoke_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $key_id = NULL) {
    $this->keyId = $key_id;
    $this->key = $this->apiKeyManager->loadKey($key_id);

    if (!$this->key) {
      $this->messenger()->addError($this->t('API key not found.'));
      return $form;
    }

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return $this->t('Are you sure you want to revoke the API key %name?', [
      '%name' => $this->key->name,
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription() {
    return $this->t('This will disable the key immediately. You can re-enable it later by editing the key.');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return new Url('nodehive_api_key_management.list');
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if ($this->apiKeyManager->revokeKey($this->keyId)) {
      $this->messenger()->addStatus($this->t('API key %name has been revoked.', [
        '%name' => $this->key->name,
      ]));
    }
    else {
      $this->messenger()->addError($this->t('Failed to revoke API key.'));
    }

    $form_state->setRedirectUrl($this->getCancelUrl());
  }

}
