<?php

declare(strict_types=1);

namespace Drupal\Tests\native_observability\Unit\EventSubscriber;

use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
use Drupal\Core\Database\Connection;
use Drupal\Tests\UnitTestCase;
use Drupal\native_observability\EventSubscriber\RequestLogExclusionSubscriber;
use Drupal\native_observability\Service\RequestLogExclusionMatcher;
use Drupal\native_observability\Service\RequestLogExclusionRepository;
use Drupal\native_observability\Service\RequestLogExclusionRuleNormalizer;
use PHPUnit\Framework\Attributes\CoversClass;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
 * Tests request-level exclusion propagation.
 */
#[CoversClass(RequestLogExclusionSubscriber::class)]
final class RequestLogExclusionSubscriberTest extends UnitTestCase {

  /**
   * Tests the subscriber sets the request attribute through the matcher.
   */
  public function testOnKernelRequestPropagatesExclusionDecision(): void {
    $cache = $this->createMock(CacheBackendInterface::class);
    $cache->method('get')
      ->willReturn((object) [
        'data' => [
          [
            'id' => 11,
            'enabled' => TRUE,
            'method' => 'GET',
            'path_match_type' => 'exact',
            'path_pattern' => '/foo/bar',
            'query_conditions' => [],
          ],
        ],
      ]);

    $matcher = new RequestLogExclusionMatcher(
      new RequestLogExclusionRepository(
        $this->createMock(Connection::class),
        $cache,
        $this->createMock(CacheTagsInvalidatorInterface::class),
        new RequestLogExclusionRuleNormalizer(),
      ),
    );
    $subscriber = new RequestLogExclusionSubscriber($matcher);
    $request = Request::create('/foo/bar', 'GET');
    $kernel = $this->createMock(HttpKernelInterface::class);
    $event = new RequestEvent($kernel, $request, HttpKernelInterface::MAIN_REQUEST);

    $subscriber->onKernelRequest($event);

    $this->assertTrue((bool) $request->attributes->get(RequestLogExclusionMatcher::ATTR_EXCLUDED));
  }

}
