<?php

declare(strict_types=1);

namespace Drupal\native_observability_spans\Form;

use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
use Drupal\native_observability_spans\Service\SpanStorageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Confirms deletion of all spans.
 */
final class DeleteAllSpansForm extends ConfirmFormBase {

  /**
   * The span storage.
   */
  private SpanStorageInterface $spanStorage;

  /**
   * Constructs the form.
   */
  public function __construct(SpanStorageInterface $span_storage) {
    $this->spanStorage = $span_storage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): self {
    return new self(
      $container->get('native_observability_spans.span_storage'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId(): string {
    return 'native_observability_spans_delete_all_spans_form';
  }

  /**
   * {@inheritdoc}
   */
  public function getQuestion(): TranslatableMarkup {
    return $this->t('Are you sure you want to delete all spans?');
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription(): TranslatableMarkup {
    return $this->t('This action permanently deletes all recorded spans.');
  }

  /**
   * {@inheritdoc}
   */
  public function getConfirmText(): TranslatableMarkup {
    return $this->t('Delete all spans');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl(): Url {
    return Url::fromRoute('native_observability_spans.spans_list');
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $deleted = $this->spanStorage->deleteAll();

    $this->messenger()->addStatus($this->t('Deleted @count spans.', [
      '@count' => $deleted,
    ]));

    $form_state->setRedirect('native_observability_spans.spans_list');
  }

}
