<?php

declare(strict_types=1);

namespace Drupal\native_observability_dashboard\Controller\Dashboard;

use Drupal\Core\Controller\ControllerBase;
use Drupal\native_observability_dashboard\Service\DashboardDatabaseBuilder;
use Drupal\native_observability_dashboard\Service\DashboardTimeRangeResolver;

/**
 * Returns the Database tab for the Native Observability dashboard.
 */
final class DatabaseController extends ControllerBase {

  /**
   * Creates a new database controller instance.
   */
  public function __construct(
    private readonly DashboardDatabaseBuilder $databaseBuilder,
    private readonly DashboardTimeRangeResolver $timeRangeResolver,
  ) {
  }

  /**
   * Builds the database dashboard tab.
   *
   * @return array
   *   A render array for the database tab.
   */
  public function overview(): array {
    $timeRange = $this->timeRangeResolver->resolve();
    $dashboard = $this->databaseBuilder->build($timeRange);

    return [
      '#theme' => 'native_observability_dashboard_database',
      '#dashboard' => $dashboard,
      '#range_selector' => $this->timeRangeResolver->buildSelectorItems(),
      '#active_range' => $timeRange->getKey(),
      '#cache' => [
        'contexts' => ['url.query_args:range'],
      ],
      '#attached' => [
        'library' => [
          'native_observability_dashboard/dashboard',
        ],
        'drupalSettings' => [
          'nativeObservabilityDashboard' => [
            'databaseObservabilityCharts' => $this->buildChartSettings($dashboard),
          ],
        ],
      ],
    ];
  }

  /**
   * Extracts chart-ready settings for the database observability section.
   *
   * @param array $dashboard
   *   The full dashboard payload.
   *
   * @return array
   *   The database observability chart settings keyed by chart id.
   */
  private function buildChartSettings(array $dashboard): array {
    $settings = [];
    $section = $dashboard['sections']['database_observability'] ?? NULL;

    if (!is_array($section) || empty($section['enabled'])) {
      return $settings;
    }

    foreach (['pressure_trend', 'request_comparison'] as $chartKey) {
      $chart = $section[$chartKey] ?? NULL;
      if (!is_array($chart) || empty($chart['enabled']) || empty($chart['chart_id'])) {
        continue;
      }

      $settings[$chart['chart_id']] = $chart;
    }

    return $settings;
  }

}
