<?php

declare(strict_types=1);

namespace Drupal\native_observability_database_observer\Form;

use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\native_observability_database_observer\Service\DatabaseObserverStorage;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Confirmation form used to delete only the currently filtered rows.
 */
final class DatabaseObserverDeleteFilteredConfirmForm extends ConfirmFormBase {

  /**
   * Creates a new delete-filtered form instance.
   */
  public function __construct(
    private readonly DatabaseObserverStorage $storage,
    private readonly RequestStack $databaseObserverRequestStack,
  ) {
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): static {
    return new static(
      $container->get(DatabaseObserverStorage::class),
      $container->get('request_stack'),
    );
  }

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

  /**
   * {@inheritdoc}
   */
  public function getQuestion(): string {
    return (string) $this->t('Are you sure you want to delete the database observer rows matching the current filters?');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl(): Url {
    return Url::fromRoute('native_observability_database_observer.report', [], [
      'query' => $this->getCurrentFilters(),
    ]);
  }

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

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

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

    $form_state->setRedirect('native_observability_database_observer.report');
  }

  /**
   * Returns the active filter set from the current request.
   */
  private function getCurrentFilters(): array {
    $request = $this->databaseObserverRequestStack->getCurrentRequest();

    if (!$request) {
      return [];
    }

    $filters = [
      'search' => (string) $request->query->get('search', ''),
      'relation_type' => (string) $request->query->get('relation_type', ''),
      'is_slow' => (string) $request->query->get('is_slow', ''),
    ];

    return array_filter(
      $filters,
      static fn($value): bool => $value !== '' && $value !== NULL
    );
  }

}
