<?php

declare(strict_types=1);

namespace Drupal\native_observability_spans\EventSubscriber;

use Drupal\native_observability\Event\NativeObservabilityEvents;
use Drupal\native_observability\Event\TracesDeletedEvent;
use Drupal\native_observability_spans\Service\SpanStorageInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Deletes spans when all traces are deleted.
 */
final class TracesDeletedSubscriber implements EventSubscriberInterface {

  /**
   * The span storage.
   */
  protected SpanStorageInterface $spanStorage;

  /**
   * Constructs the subscriber.
   */
  public function __construct(SpanStorageInterface $span_storage) {
    $this->spanStorage = $span_storage;
  }

  /**
   * Reacts to a global trace purge event.
   *
   * When all traces are deleted from the system, spans must also be removed
   * to keep storage consistent and avoid orphan records.
   */
  public function onTracesDeleted(TracesDeletedEvent $event): void {
    // Keep spans consistent with traces after a global purge.
    $this->spanStorage->deleteAll();
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    return [
      NativeObservabilityEvents::TRACES_DELETED => 'onTracesDeleted',
    ];
  }

}
