<?php

declare(strict_types=1);

namespace Drupal\native_observability_cache_observer\Form;

use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\native_observability_cache_observer\Service\CacheObserverStorage;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Confirmation form for deleting filtered cache observer records.
 */
final class CacheObserverDeleteFilteredConfirmForm extends ConfirmFormBase {

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

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

  /**
   * {@inheritdoc}
   */
  public function getQuestion(): string {
    return (string) $this->t('Delete the currently filtered cache observer records?');
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription(): string {
    return (string) $this->t('This action deletes stored observability records only. It does not clear Drupal runtime caches.');
  }

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

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

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

    $filters = [
      'search' => (string) $request?->query->get('search', ''),
      'event_type' => (string) $request?->query->get('event_type', ''),
      'cache_layer' => (string) $request?->query->get('cache_layer', ''),
      'status' => (string) $request?->query->get('status', ''),
      'method' => (string) $request?->query->get('method', ''),
      'route_name' => (string) $request?->query->get('route_name', ''),
      'path' => (string) $request?->query->get('path', ''),
      'request_id' => (string) $request?->query->get('request_id', ''),
      'has_request_id' => (string) $request?->query->get('has_request_id', ''),
      'uncacheable_only' => (string) $request?->query->get('uncacheable_only', ''),
    ];

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

    $count = $this->storage->deleteByFilters($filters, 5000);

    $this->messenger()->addStatus($this->t('Deleted @count filtered cache observer record(s).', [
      '@count' => $count,
    ]));

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

}
