<?php

declare(strict_types=1);

namespace Drupal\native_observability_dashboard\Controller\Dashboard;

use Drupal\Core\Controller\ControllerBase;
use Drupal\native_observability_dashboard\Service\DashboardCacheBuilder;
use Drupal\native_observability_dashboard\Service\DashboardTimeRangeResolver;
use Symfony\Component\HttpFoundation\Response;

/**
 * Returns the Cache tab for the Native Observability dashboard.
 */
final class CacheController extends ControllerBase {

  /**
   * Creates a new cache controller instance.
   *
   * @param \Drupal\native_observability_dashboard\Service\DashboardCacheBuilder $cacheBuilder
   *   The cache dashboard builder service.
   * @param \Drupal\native_observability_dashboard\Service\DashboardTimeRangeResolver $timeRangeResolver
   *   The dashboard time range resolver service.
   */
  public function __construct(
    private readonly DashboardCacheBuilder $cacheBuilder,
    private readonly DashboardTimeRangeResolver $timeRangeResolver,
  ) {
  }

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

    return [
      '#theme' => 'native_observability_dashboard_cache',
      '#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' => [
            'cacheObservabilityCharts' => $this->buildCacheObservabilityChartSettings($dashboard),
          ],
        ],
      ],
    ];
  }

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

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

    $trend = $section['activity_trend'] ?? NULL;
    if (!is_array($trend) || empty($trend['enabled']) || empty($trend['chart_id'])) {
      return $settings;
    }

    $settings[$trend['chart_id']] = [
      'chart_id' => $trend['chart_id'],
      'series' => $trend['series'] ?? [],
    ];

    return $settings;
  }

  /**
   * Exports cache runtime records as CSV.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   The CSV response.
   */
  public function exportRuntimeRecords() {
    $timeRange = $this->timeRangeResolver->resolve();
    $dashboard = $this->cacheBuilder->build($timeRange);
    $section = $dashboard['sections']['cache_observability']['runtime_records'] ?? [];
    $rows = $section['rows'] ?? [];

    $handle = fopen('php://temp', 'r+');
    fputcsv($handle, ['time', 'event_type', 'cache_layer', 'method', 'context', 'status']);

    foreach ($rows as $row) {
      fputcsv($handle, [
        $row['time'] ?? '',
        $row['event_type'] ?? '',
        $row['cache_layer'] ?? '',
        $row['method'] ?? '',
        $row['context'] ?? '',
        $row['status'] ?? '',
      ]);
    }

    rewind($handle);
    $csv = stream_get_contents($handle);
    fclose($handle);

    return new Response(
      $csv,
      200,
      [
        'Content-Type' => 'text/csv; charset=UTF-8',
        'Content-Disposition' => 'attachment; filename="cache-runtime-records.csv"',
      ]
    );
  }

}
