<?php

declare(strict_types=1);

namespace Drupal\nodehive_path_alias\PageCache;

use Drupal\Core\PageCache\RequestPolicyInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Denies page caching for router translate-path requests with a Bearer token.
 *
 * The Drupal page cache (stack middleware) runs before authentication and keys
 * responses by URL only. Requests to /router/translate-path with different
 * Bearer tokens would receive the same cached response. This policy prevents
 * the page cache from serving stale space-specific responses.
 */
final class RouterApiKeyRequestPolicy implements RequestPolicyInterface {

  /**
   * {@inheritdoc}
   */
  public function check(Request $request): ?string {
    if (!str_contains($request->getPathInfo(), '/router/translate-path')) {
      return NULL;
    }

    $auth = $request->headers->get('Authorization', '');
    if (str_starts_with(strtolower($auth), 'bearer ')) {
      return self::DENY;
    }

    return NULL;
  }

}
