<?php

declare(strict_types=1);

namespace Drupal\native_observability_database_observer\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Link;
use Drupal\Core\Pager\PagerManagerInterface;
use Drupal\Core\Url;
use Drupal\native_observability\Service\TraceStorageInterface;
use Drupal\native_observability_database_observer\Form\DatabaseObserverFiltersForm;
use Drupal\native_observability_database_observer\Service\DatabaseObserverStorage;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Builds the RAW listing page for captured slow database query rows.
 */
final class DatabaseObserverListController extends ControllerBase {

  /**
   * Creates a new listing controller instance.
   */
  public function __construct(
    private readonly DatabaseObserverStorage $storage,
    private readonly TraceStorageInterface $traceStorage,
    private readonly PagerManagerInterface $pagerManager,
    private readonly RequestStack $databaseObserverRequestStack,
  ) {
  }

  /**
   * Builds the report page.
   */
  public function list(): array {
    $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
    );

    $limit = 50;
    $total = $this->storage->count($filters);
    $pager = $this->pagerManager->createPager($total, $limit);
    $offset = $pager->getCurrentPage() * $limit;
    $rows = $this->storage->search($filters, $limit, $offset);

    $tableRows = [];
    foreach ($rows as $row) {
      $id = (int) $row['id'];

      $routePathMarkup = [
        '#type' => 'container',
        'route' => [
          '#markup' => '<div><strong>' . $this->t('@value', [
            '@value' => (string) ($row['route_name'] ?: '-'),
          ]) . '</strong></div>',
        ],
        'separator' => [
          '#markup' => '<hr style="margin:6px 0;">',
        ],
        'path' => [
          '#markup' => '<div style="font-size:12px; color:#6b7280;">' . $this->t('@value', [
            '@value' => (string) ($row['path'] ?: '-'),
          ]) . '</div>',
        ],
      ];

      $requestTraceMarkup = [
        '#type' => 'container',
        'request_id' => [
          '#markup' => '<div>' . $this->t('@value', [
            '@value' => (string) ($row['request_id'] ?: '-'),
          ]) . '</div>',
        ],
      ];

      if (!empty($row['request_id']) && $this->traceStorage->loadByRequestId((string) $row['request_id'])) {
        $requestTraceMarkup['trace'] = [
          '#markup' => '<div style="margin-top:6px;">' . Link::fromTextAndUrl(
              (string) $this->t('Open trace'),
              Url::fromRoute('native_observability.trace_view_by_request_id', [
                'request_id' => $row['request_id'],
              ])
          )->toString() . '</div>',
        ];
      }

      $tableRows[] = [
        [
          'data' => Link::fromTextAndUrl(
            (string) $id,
            Url::fromRoute('native_observability_database_observer.view', ['id' => $id])
          )->toString(),
        ],
        ['data' => (string) $row['relation_type']],
        ['data' => $routePathMarkup],
        ['data' => number_format((float) $row['duration_ms'], 3) . ' ms'],
        ['data' => !empty($row['is_slow']) ? (string) $this->t('Yes') : (string) $this->t('No')],
        ['data' => $requestTraceMarkup],
        ['data' => (string) $row['created_at_formatted']],
      ];
    }

    return [
      '#type' => 'container',
      'filters' => $this->formBuilder()->getForm(DatabaseObserverFiltersForm::class),
      'summary' => [
        '#type' => 'container',
        '#attributes' => [
          'class' => ['messages', 'messages--status'],
          'style' => 'margin-bottom:16px; padding:12px; border-left:4px solid #0d6efd;',
        ],
        'text' => [
          '#markup' => '<strong>' . $this->t('Database RAW observer') . '</strong><div style="margin-top:6px;">'
          . $this->t('This RAW page stores only slow queries above the configured threshold. Aggregated per-request database counters are intended for the trace payload and are not listed row-by-row here.')
          . '</div>',
        ],
      ],
      'table' => [
        '#type' => 'table',
        '#header' => [
          $this->t('ID'),
          $this->t('Relation'),
          $this->t('Route / Path'),
          $this->t('Duration'),
          $this->t('Slow'),
          $this->t('Request / Trace'),
          $this->t('Created'),
        ],
        '#rows' => $tableRows,
        '#empty' => $this->t('No slow database queries have been stored yet for the current threshold.'),
      ],
      'pager' => ['#type' => 'pager'],
    ];
  }

}
