<?php

declare(strict_types=1);

namespace Drupal\native_observability\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\native_observability\Service\DiagnosticsService;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides the Native Observability status page.
 */
final class NativeObservabilityStatusController extends ControllerBase {

  public function __construct(
    private readonly DiagnosticsService $diagnostics,
  ) {
  }

  /**
   * Creates the controller instance.
   *
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   *   The service container.
   *
   * @return self
   *   The controller instance.
   */
  public static function create(ContainerInterface $container): self {
    return new self(
      $container->get('native_observability.diagnostics'),
    );
  }

  /**
   * Status page callback.
   */
  public function status(): array {
    $data = $this->diagnostics->collect();

    $rows = [];
    foreach ($data as $key => $value) {
      $rows[] = [$key, is_scalar($value) ? (string) $value : json_encode($value)];
    }

    return [
      '#type' => 'container',
      'intro' => [
        '#markup' => '<p>Quick runtime snapshot (no secrets).</p>',
      ],
      'table' => [
        '#type' => 'table',
        '#header' => ['Key', 'Value'],
        '#rows' => $rows,
        '#empty' => $this->t('No data available.'),
      ],
      '#cache' => [
        'max-age' => 0,
      ],
    ];
  }

}
