<?php

declare(strict_types=1);

namespace Drupal\visitors\Service;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\visitors\VisitorsSpamInterface;

/**
 * Service for detecting spam referrers.
 */
final class SpamService implements VisitorsSpamInterface {

  /**
   * The spam sites.
   *
   * @var array
   */
  private array $spamSites;

  /**
   * Constructs a new SpamService.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The configuration factory.
   */
  public function __construct(ConfigFactoryInterface $config_factory) {
    $this->spamSites = $config_factory->get('visitors.spam')->get('sites') ?? [];
  }

  /**
   * {@inheritdoc}
   */
  public function match(string $host): bool {

    // Check if domain matches any spam site.
    foreach ($this->spamSites as $spam_site) {
      if ($this->isDomainMatch($host, $spam_site)) {
        return TRUE;
      }
    }

    return FALSE;
  }

  /**
   * Checks if a domain matches a spam site pattern.
   *
   * @param string $domain
   *   The normalized domain to check.
   * @param string $spam_site
   *   The spam site pattern to match against.
   *
   * @return bool
   *   TRUE if the domain matches the spam site pattern.
   */
  private function isDomainMatch(string $domain, string $spam_site): bool {
    $domain = strtolower(trim($domain));
    $spam_site = strtolower(trim($spam_site));

    // Exact match.
    if ($domain === $spam_site || str_ends_with($domain, '.' . $spam_site)) {
      return TRUE;
    }

    return FALSE;
  }

}
