<?php

declare(strict_types=1);

namespace Drupal\native_observability_database_observer\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\native_observability_database_observer\Service\DatabaseObserverStorage;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Returns JSON exports for one row or for a filtered RAW subset.
 */
final class DatabaseObserverExportController extends ControllerBase {

  /**
   * Creates a new export controller instance.
   */
  public function __construct(
    private readonly DatabaseObserverStorage $storage,
    private readonly RequestStack $databaseObserverRequestStack,
  ) {
  }

  /**
   * Exports one record as JSON.
   */
  public function export(int $id): JsonResponse {
    $record = $this->storage->load($id);
    if (!$record) {
      throw $this->createNotFoundException();
    }

    return new JsonResponse($record);
  }

  /**
   * Exports the currently filtered row set as JSON.
   */
  public function exportFiltered(): JsonResponse {
    $request = $this->databaseObserverRequestStack->getCurrentRequest();

    $filters = [
      'search' => (string) $request?->query->get('search', ''),
      'relation_type' => (string) $request?->query->get('relation_type', ''),
      'is_slow' => (string) $request?->query->get('is_slow', ''),
    ];

    $filters = array_filter(
      $filters,
      static fn($value): bool => $value !== '' && $value !== NULL
    );

    return new JsonResponse([
      'filters' => $filters,
      'count' => $this->storage->count($filters),
      'items' => $this->storage->search($filters, 500, 0),
    ]);
  }

}
