<?php

declare(strict_types=1);

namespace Drupal\native_observability_report\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\TempStore\PrivateTempStoreFactory;
use Drupal\native_observability_report\Service\ObservabilityReportDocumentBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;

/**
 * Exports prepared observability report snapshots.
 */
final class ObservabilityReportExportController extends ControllerBase {

  /**
   * Creates a new export controller instance.
   */
  public function __construct(
    protected PrivateTempStoreFactory $tempStoreFactory,
    protected ObservabilityReportDocumentBuilder $documentBuilder,
  ) {}

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

  /**
   * Exports the prepared report as printable HTML.
   */
  public function exportHtml(string $export_key): Response {
    $preview = $this->loadPreview($export_key);
    $html = $this->documentBuilder->buildHtmlDocument($preview, FALSE);

    return new Response($html, 200, [
      'Content-Type' => 'text/html; charset=UTF-8',
    ]);
  }

  /**
   * Loads a prepared preview snapshot from the private temp store.
   */
  private function loadPreview(string $export_key): array {
    $preview = $this->tempStoreFactory->get('native_observability_report')->get($export_key);

    if (!is_array($preview) || $preview === []) {
      throw $this->createNotFoundException();
    }

    return $preview;
  }

}
