<?php

declare(strict_types=1);

namespace Drupal\native_observability_database_observer\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Configuration form for the Database Observer submodule.
 */
final class DatabaseObserverSettingsForm extends ConfigFormBase {

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

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames(): array {
    return ['native_observability_database_observer.settings'];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state): array {
    $config = $this->config('native_observability_database_observer.settings');

    $form['intro'] = [
      '#type' => 'details',
      '#title' => $this->t('How this observer behaves'),
      '#open' => TRUE,
      'text' => [
        '#markup' => '<p>' . $this->t('This observer is optimized for lightweight runtime counting. Normal query counters stay in memory during the request and are intended for trace enrichment. Only slow queries above the configured threshold are persisted in the RAW database table.') . '</p>',
      ],
    ];

    $form['capture_enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable database observer capture'),
      '#default_value' => (bool) $config->get('capture_enabled'),
      '#description' => $this->t('Disables capture without requiring module uninstallation. This is useful during benchmarks, maintenance windows or controlled production tests.'),
    ];

    $form['performance_reference'] = [
      '#type' => 'details',
      '#title' => $this->t('Reference timing guidance'),
      '#open' => TRUE,
      'items' => [
        '#theme' => 'item_list',
        '#items' => [
          $this->t('Under 20 ms: usually very fast for interactive rendering.'),
          $this->t('Between 20 ms and 100 ms: acceptable in many contexts, but worth watching when repeated frequently.'),
          $this->t('Above 100 ms: commonly considered slow for regular page rendering.'),
          $this->t('Above 250 ms: typically high-impact and should be investigated quickly.'),
        ],
      ],
    ];

    $form['slow_query_threshold_ms'] = [
      '#type' => 'number',
      '#title' => $this->t('Slow query threshold (ms)'),
      '#default_value' => (int) ($config->get('slow_query_threshold_ms') ?? 100),
      '#min' => 1,
      '#step' => 1,
      '#required' => TRUE,
      '#description' => $this->t('Only queries above this duration are stored in RAW storage. Lower this value temporarily when you want to verify the persistence flow.'),
    ];

    $form['store_slow_query_text'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Store SQL text for slow queries'),
      '#default_value' => (bool) $config->get('store_slow_query_text'),
      '#description' => $this->t('When enabled, SQL text is persisted only for rows above the threshold. Disable this when the project needs an even smaller storage footprint.'),
    ];

    $form['max_stored_queries_per_request'] = [
      '#type' => 'number',
      '#title' => $this->t('Maximum stored slow queries per request'),
      '#default_value' => (int) ($config->get('max_stored_queries_per_request') ?? 20),
      '#min' => 1,
      '#step' => 1,
      '#required' => TRUE,
      '#description' => $this->t('Hard safety limit used to avoid large writes when a single request produces many slow queries.'),
    ];

    $form['retention_hours'] = [
      '#type' => 'number',
      '#title' => $this->t('Retention period (hours)'),
      '#default_value' => (int) ($config->get('retention_hours') ?? 72),
      '#min' => 1,
      '#step' => 1,
      '#required' => TRUE,
      '#description' => $this->t('Old RAW records are deleted by the shared Native Observability cleanup flow.'),
    ];

    $form['report_limit'] = [
      '#type' => 'number',
      '#title' => $this->t('Default report limit'),
      '#default_value' => (int) ($config->get('report_limit') ?? 100),
      '#min' => 10,
      '#step' => 10,
      '#required' => TRUE,
      '#description' => $this->t('Administrative report pages can use this value as a safe upper bound for recent rows.'),
    ];

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $this->configFactory->getEditable('native_observability_database_observer.settings')
      ->set('capture_enabled', (bool) $form_state->getValue('capture_enabled'))
      ->set('slow_query_threshold_ms', (int) $form_state->getValue('slow_query_threshold_ms'))
      ->set('store_slow_query_text', (bool) $form_state->getValue('store_slow_query_text'))
      ->set('max_stored_queries_per_request', (int) $form_state->getValue('max_stored_queries_per_request'))
      ->set('retention_hours', (int) $form_state->getValue('retention_hours'))
      ->set('report_limit', (int) $form_state->getValue('report_limit'))
      ->save();

    parent::submitForm($form, $form_state);
  }

}
