<?php

declare(strict_types=1);

namespace Drupal\native_observability_otel\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\native_observability\Service\TraceStorageInterface;
use Drupal\native_observability_otel\Service\ElasticTelemetryBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Exports traces in Elastic-compatible NDJSON format.
 */
final class ElasticTelemetryExportController extends ControllerBase {

  /**
   * Constructor.
   */
  public function __construct(
    private readonly TraceStorageInterface $traceStorage,
    private readonly ElasticTelemetryBuilder $builder,
  ) {
  }

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

  /**
   * Export endpoint.
   */
  public function export(Request $request): Response {
    $limit = max(1, min(1000, (int) $request->query->get('limit', 200)));

    $filters = [
      'status_code' => $request->query->get('status_code'),
      'path' => $request->query->get('path'),
      'min_duration_ms' => $request->query->get('min_duration_ms'),
      'max_duration_ms' => $request->query->get('max_duration_ms'),
    ];

    $traces = $this->traceStorage->search($filters, $limit, 0);
    $output = $this->builder->buildNdjson($traces);

    $response = new Response($output);
    $response->headers->set('Content-Type', 'application/x-ndjson; charset=UTF-8');

    return $response;
  }

}
