<?php

declare(strict_types=1);

namespace Drupal\native_observability_metrics\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\native_observability_metrics\Service\RouteMetricsAggregator;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a manual action to run route metrics aggregation immediately.
 */
final class MetricsAggregationRunForm extends FormBase {

  /**
   * Constructs the manual aggregation form.
   *
   * @param \Drupal\native_observability_metrics\Service\RouteMetricsAggregator $routeMetricsAggregator
   *   Route metrics aggregator service.
   */
  public function __construct(
    private readonly RouteMetricsAggregator $routeMetricsAggregator,
  ) {
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state): array {
    $form['description'] = [
      '#type' => 'item',
      '#markup' => $this->t('Run route metrics aggregation immediately for the latest completed aggregation window.'),
    ];

    $form['actions'] = [
      '#type' => 'actions',
    ];

    $form['actions']['run_aggregation_now'] = [
      '#type' => 'submit',
      '#value' => $this->t('Run aggregation now'),
      '#button_type' => 'primary',
    ];

    return $form;
  }

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

    if (empty($metrics)) {
      $this->messenger()->addWarning($this->t('No completed aggregation window was available. Generate trace traffic, wait for the current window to finish, and try again.'));
    }
    else {
      $this->messenger()->addStatus($this->t('Metrics aggregation completed successfully. Generated @count aggregated route snapshots.', [
        '@count' => count($metrics),
      ]));
    }

    $form_state->setRedirect('native_observability_metrics.dashboard');
  }

}
