<?php

declare(strict_types=1);

namespace Drupal\visitors\Service;

use Drupal\Core\Config\ConfigFactoryInterface;

/**
 * Base class for hostname matching services.
 */
abstract class HostnameMatcherServiceBase {

  /**
   * The config factory service.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected ConfigFactoryInterface $configFactory;

  /**
   * Cached configuration data.
   *
   * @var array|null
   */
  protected ?array $cachedConfig = NULL;

  /**
   * Constructs a new HostnameMatcherServiceBase.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory service.
   */
  public function __construct(ConfigFactoryInterface $config_factory) {
    $this->configFactory = $config_factory;
  }

  /**
   * Match a hostname against the configured list.
   *
   * @param string $hostname
   *   The hostname to match.
   *
   * @return string|null
   *   The label if matched, null otherwise.
   */
  public function match(string $hostname): ?string {
    if (empty($hostname)) {
      return NULL;
    }

    $config = $this->getConfig();
    $normalized_hostname = strtolower(trim($hostname));

    foreach ($config as $item) {
      if (isset($item['label']) && isset($item['hosts']) && is_array($item['hosts'])) {
        foreach ($item['hosts'] as $host) {
          if (strtolower(trim($host)) === $normalized_hostname) {
            return $item['label'];
          }
        }
      }
    }

    return NULL;
  }

  /**
   * Get the configuration data.
   *
   * @return array
   *   The configuration data.
   */
  abstract protected function getConfig(): array;

}
