<?php

declare(strict_types=1);

namespace Drupal\native_observability\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\native_observability\Service\TraceStorageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Exports a trace payload as JSON.
 *
 * The export is intended for:
 * - incident tickets
 * - sharing traces with teammates
 * - external tooling ingestion.
 */
final class TraceExportController extends ControllerBase {

  /**
   * Constructs the controller.
   *
   * @param \Drupal\native_observability\Service\TraceStorageInterface $storage
   *   Trace storage service.
   */
  public function __construct(
    private readonly TraceStorageInterface $storage,
  ) {
  }

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

  /**
   * Export callback.
   *
   * @param int $id
   *   Trace ID.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   JSON response with download headers.
   */
  public function export(int $id): Response {
    $trace = $this->storage->load($id);
    if (!$trace) {
      throw new NotFoundHttpException('Trace not found.');
    }

    // Export the stored payload if present; otherwise build a minimal JSON.
    $payload = (string) ($trace['payload'] ?? '');
    if ($payload === '') {
      $payload = json_encode([
        'meta' => [
          'id' => (int) $trace['id'],
          'request_id' => (string) $trace['request_id'],
          'method' => (string) $trace['method'],
          'path' => (string) $trace['path'],
          'status_code' => $trace['status_code'],
          'duration_ms' => $trace['duration_ms'],
          'started_at' => $trace['started_at'],
          'ended_at' => $trace['ended_at'],
        ],
      ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?: '{}';
    }

    $request_id = preg_replace('/[^A-Za-z0-9_-]/', '_', (string) $trace['request_id']);
    $filename = 'trace_' . $request_id . '.json';

    $response = new Response($payload);
    $response->headers->set('Content-Type', 'application/json; charset=UTF-8');
    $response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"');

    return $response;
  }

}
