<?php

declare(strict_types=1);

namespace Drupal\native_observability\EventSubscriber;

use Drupal\native_observability\Service\RequestLogExclusionMatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Evaluates request-log exclusion rules early in the main request lifecycle.
 */
final class RequestLogExclusionSubscriber implements EventSubscriberInterface {

  public function __construct(
    private readonly RequestLogExclusionMatcher $matcher,
  ) {
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    return [
      KernelEvents::REQUEST => ['onKernelRequest', 1500],
    ];
  }

  /**
   * Computes the exclusion decision once and stores it on the request.
   */
  public function onKernelRequest(RequestEvent $event): void {
    if (!$event->isMainRequest()) {
      return;
    }

    try {
      $this->matcher->isExcluded($event->getRequest());
    }
    catch (\Throwable) {
      // Fail-safe: request flow must continue even if exclusion resolution
      // cannot be computed.
      $event->getRequest()->attributes->set(RequestLogExclusionMatcher::ATTR_EXCLUDED, FALSE);
    }
  }

}
