<?php

declare(strict_types=1);

namespace Drupal\native_observability_cache_observer\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Url;
use Drupal\native_observability_cache_observer\Service\CacheObserverStorage;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

/**
 * Displays raw cache observer event details.
 *
 * This page shows:
 * - Core cache observer metadata
 * - Stored JSON payload in a collapsible details element.
 */
final class CacheObserverViewController extends ControllerBase {

  /**
   * Creates a new cache observer view controller instance.
   */
  public function __construct(
    private readonly CacheObserverStorage $storage,
    #[Autowire(service: 'date.formatter')]
    private readonly DateFormatterInterface $dateFormatter,
  ) {
  }

  /**
   * Builds the detail page for a raw cache observer event.
   */
  public function view(int $id): array {
    $record = $this->storage->load($id);
    if (!$record) {
      throw new NotFoundHttpException('Cache observer event not found.');
    }

    $payloadRaw = json_encode(
      $record['payload'] ?? [],
      JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
    ) ?: '{}';
    $createdAtFormatted = !empty($record['created_at'])
      ? $this->dateFormatter->format((int) $record['created_at'], 'short')
      : '';

    $items = [
      $this->t('ID: @value', ['@value' => (string) ($record['id'] ?? '')]),
      $this->t('Event type: @value', ['@value' => (string) ($record['event_type'] ?? '')]),
      $this->t('Layer: @value', ['@value' => (string) ($record['cache_layer'] ?? '')]),
      $this->t('Status: @value', ['@value' => (string) ($record['status'] ?? '')]),
      $this->t('Method: @value', ['@value' => (string) ($record['method'] ?? '')]),
      $this->t('Path: @value', ['@value' => (string) ($record['path'] ?? '')]),
      $this->t('Route: @value', ['@value' => (string) ($record['route_name'] ?? '')]),
      $this->t('Request ID: @value', ['@value' => (string) ($record['request_id'] ?? '')]),
      $this->t('Tag count: @value', ['@value' => (string) ($record['tag_count'] ?? 0)]),
      $this->t('Context count: @value', ['@value' => (string) ($record['context_count'] ?? 0)]),
      $this->t('Max-age: @value', ['@value' => (string) ($record['max_age'] ?? '')]),
      $this->t('Created: @value', ['@value' => $createdAtFormatted]),
    ];

    return [
      '#type' => 'container',

      // Action buttons.
      'actions' => [
        '#type' => 'container',
        '#attributes' => [
          'style' => 'margin-bottom:12px; display:flex; gap:8px; flex-wrap:wrap;',
        ],
        'back' => [
          '#type' => 'link',
          '#title' => $this->t('Back to cache observer'),
          '#url' => Url::fromRoute('native_observability_cache_observer.report'),
          '#attributes' => [
            'class' => ['button'],
          ],
        ],
        'export' => [
          '#type' => 'link',
          '#title' => $this->t('Export JSON'),
          '#url' => Url::fromRoute('native_observability_cache_observer.export', ['id' => $id]),
          '#attributes' => [
            'class' => ['button'],
          ],
        ],
      ],

      // Metadata summary.
      'meta' => [
        '#theme' => 'item_list',
        '#title' => $this->t('Cache observer metadata'),
        '#items' => $items,
      ],

      // Collapsible JSON payload, aligned with the trace detail page pattern.
      'payload' => [
        '#type' => 'details',
        '#title' => $this->t('Payload (JSON)'),
        '#open' => TRUE,
        'content' => [
          '#type' => 'textarea',
          '#value' => $payloadRaw,
          '#attributes' => [
            'readonly' => 'readonly',
            'style' => 'font-family: monospace; min-height: 420px;',
          ],
        ],
      ],

      '#cache' => [
        'max-age' => 0,
      ],
    ];
  }

}
