<?php

declare(strict_types=1);

namespace Drupal\native_observability\Form;

use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\native_observability\Service\RequestLogExclusionRepository;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Deletes one request-log exclusion rule.
 */
final class RequestLogExclusionRuleDeleteForm extends ConfirmFormBase {

  /**
   * Current rule ID.
   */
  private int $ruleId = 0;

  public function __construct(
    private readonly RequestLogExclusionRepository $repository,
  ) {
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function getQuestion(): string {
    return $this->t('Delete this exclusion rule?');
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, ?int $id = NULL): array {
    $this->ruleId = (int) ($id ?? 0);
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $this->repository->delete($this->ruleId);
    $this->messenger()->addStatus($this->t('The exclusion rule has been deleted.'));
    $form_state->setRedirect('native_observability.request_log_exclusion_list');
  }

}
