<?php

declare(strict_types=1);

namespace Drupal\nodehive_path_alias;

use Drupal\Core\Database\Connection;

/**
 * Resolves path aliases scoped to a NodeHive space.
 *
 * Shared by both event subscribers to avoid duplication.
 */
final class PathAliasSpaceLookup implements PathAliasSpaceLookupInterface {

  public function __construct(
    private readonly Connection $database,
  ) {}

  /**
   * Returns the system path for an alias within a space, or NULL if not found.
   *
   * Tries the given langcode first, then language-neutral ('und').
   *
   * @param string $alias
   *   The URL alias (e.g. '/about').
   * @param int $spaceId
   *   The integer space ID.
   * @param string|null $langcode
   *   Optional content language code.
   *
   * @return string|null
   *   The system path (e.g. '/node/42') or NULL.
   */
  public function resolve(string $alias, int $spaceId, ?string $langcode): ?string {
    $langcodes = array_unique(array_filter([$langcode, 'und']));

    foreach ($langcodes as $code) {
      $result = $this->database->select('path_alias', 'pa')
        ->fields('pa', ['path'])
        ->condition('alias', $alias)
        ->condition('nodehive_space', $spaceId)
        ->condition('langcode', $code)
        ->condition('status', 1)
        ->range(0, 1)
        ->execute()
        ->fetchField();

      if ($result !== FALSE) {
        return (string) $result;
      }
    }

    // Fallback: no langcode match found — return the first alias for this
    // space regardless of language. This handles the common case where the
    // frontend omits the ?langcode= param but the alias is stored with a
    // specific language code (e.g. 'cs').
    $result = $this->database->select('path_alias', 'pa')
      ->fields('pa', ['path'])
      ->condition('alias', $alias)
      ->condition('nodehive_space', $spaceId)
      ->condition('status', 1)
      ->range(0, 1)
      ->execute()
      ->fetchField();

    return $result !== FALSE ? (string) $result : NULL;
  }

}
