<?php

declare(strict_types=1);

namespace Drupal\native_observability_database_observer\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\native_observability\Service\TraceStorageInterface;
use Drupal\native_observability_database_observer\Service\DatabaseObserverStorage;

/**
 * Displays the full details for a single raw database observer record.
 */
final class DatabaseObserverViewController extends ControllerBase {

  /**
   * Creates a new detail controller instance.
   */
  public function __construct(
    private readonly DatabaseObserverStorage $storage,
    private readonly TraceStorageInterface $traceStorage,
  ) {
  }

  /**
   * Builds the detail page.
   */
  public function view(
    int $id,
  ): array {
    $record = $this->storage->load($id);
    if (!$record) {
      throw $this->createNotFoundException();
    }

    $items = [
      $this->t('ID: @value', ['@value' => (string) $record['id']]),
      $this->t('Relation type: @value', ['@value' => (string) $record['relation_type']]),
      $this->t('Method: @value', ['@value' => (string) $record['method']]),
      $this->t('Path: @value', ['@value' => (string) $record['path']]),
      $this->t('Route name: @value', ['@value' => (string) $record['route_name']]),
      $this->t('Duration: @value ms', ['@value' => number_format((float) $record['duration_ms'], 3)]),
      $this->t('Connection key: @value', ['@value' => (string) $record['connection_key']]),
      $this->t('Connection target: @value', ['@value' => (string) $record['connection_target']]),
      $this->t('Request ID: @value', ['@value' => (string) $record['request_id']]),
      $this->t('Created: @value', ['@value' => (string) $record['created_at_formatted']]),
      $this->t('Query hash: @value', ['@value' => (string) $record['query_hash']]),
      $this->t('Caller: @value', ['@value' => (string) $record['caller']]),
    ];

    $build = [
      '#type' => 'container',
      'meta' => [
        '#theme' => 'item_list',
        '#items' => $items,
      ],
    ];

    if (!empty($record['request_id']) && $this->traceStorage->loadByRequestId((string) $record['request_id'])) {
      $build['trace_link'] = [
        '#markup' => '<p>' . Link::fromTextAndUrl(
            (string) $this->t('Open correlated trace'),
            Url::fromRoute('native_observability.trace_view_by_request_id', ['request_id' => $record['request_id']])
        )->toString() . '</p>',
      ];
    }

    $build['query_text'] = [
      '#type' => 'details',
      '#title' => $this->t('SQL text'),
      '#open' => TRUE,
      'value' => [
        '#markup' => '<pre style="white-space:pre-wrap; overflow:auto; max-height:320px;">' . htmlspecialchars((string) $record['query_text']) . '</pre>',
      ],
    ];

    $build['payload'] = [
      '#type' => 'details',
      '#title' => $this->t('Stored payload'),
      '#open' => TRUE,
      'value' => [
        '#markup' => '<pre style="white-space:pre-wrap; overflow:auto; max-height:420px;">' . htmlspecialchars(json_encode($record['payload'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)) . '</pre>',
      ],
    ];

    return $build;
  }

}
