<?php

namespace Drupal\nodehive_api_key_management\Authentication;

use Drupal\Core\Authentication\AuthenticationProviderInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AnonymousUserSession;
use Drupal\nodehive_api_key_management\Service\ApiKeyManager;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * API Key authentication provider.
 *
 * Accepts Authorization: Bearer <api_key> for protected routes.
 */
class ApiKeyAuthenticationProvider implements AuthenticationProviderInterface {

  /**
   * The API key manager service.
   *
   * @var \Drupal\nodehive_api_key_management\Service\ApiKeyManager
   */
  protected $apiKeyManager;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The logger service.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * Constructs an ApiKeyAuthenticationProvider object.
   */
  public function __construct(
    ApiKeyManager $api_key_manager,
    EntityTypeManagerInterface $entity_type_manager,
    LoggerInterface $logger,
  ) {
    $this->apiKeyManager = $api_key_manager;
    $this->entityTypeManager = $entity_type_manager;
    $this->logger = $logger;
  }

  /**
   * {@inheritdoc}
   */
  public function applies(Request $request) {
    $path = $request->getPathInfo();

    // Apply to JSON:API and REST API endpoints.
    // Note: CDP API uses session-based authentication, so it's excluded.
    $protected_paths = [
      '/jsonapi',
      '/api',
    ];

    foreach ($protected_paths as $protected_path) {
      if (str_starts_with($path, $protected_path)) {
        // Check for Bearer token.
        $auth = $request->headers->get('Authorization') ?? '';
        if (str_starts_with(strtolower($auth), 'bearer ')) {
          return TRUE;
        }
      }
    }

    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function authenticate(Request $request) {
    $auth = $request->headers->get('Authorization');
    if (!$auth) {
      return NULL;
    }

    // Extract the token after "Bearer ".
    $token = trim(substr($auth, 7));

    // Validate the API key.
    $key_record = $this->apiKeyManager->validateKey($token);

    if (!$key_record) {
      $this->logger->warning('Invalid API key used on @path from IP @ip', [
        '@path' => $request->getPathInfo(),
        '@ip' => $request->getClientIp(),
      ]);
      return NULL;
    }

    // Load the user account associated with this API key.
    $user_storage = $this->entityTypeManager->getStorage('user');
    $account = $user_storage->load($key_record->uid);

    if ($account) {
      return $account;
    }

    // Fallback to anonymous if user doesn't exist.
    $this->logger->error('User ID @uid for API key @prefix not found. API key authentication failed.', [
      '@uid' => $key_record->uid,
      '@prefix' => $key_record->key_prefix,
    ]);
    return new AnonymousUserSession();
  }

  /**
   * {@inheritdoc}
   */
  public function challenge(Request $request) {
    // Return WWW-Authenticate header for 401 responses.
    return ['WWW-Authenticate' => 'Bearer realm="api"'];
  }

}
