<?php
/**
 * @package Hafenstudios\Wellenbrecher
 */

namespace Hafenstudios\Wellenbrecher\Rules;

use Hafenstudios\Wellenbrecher\Engine\Context;
use Hafenstudios\Wellenbrecher\Engine\RuleResult;
use Hafenstudios\Wellenbrecher\Support\Text;

defined( 'ABSPATH' ) || exit;

/**
 * Billig-TLD (.xyz, .top, .click, ...) in verlinkten Domains: schwaches
 * Einzelsignal (+5), das erst in Kombination wirkt.
 */
class CheapTldRule extends AbstractRule {

	public const ID             = 'cheap_tld';
	public const DEFAULT_POINTS = 5;

	/**
	 * TLD-Liste ohne fuehrenden Punkt.
	 *
	 * @var array<string, bool>
	 */
	protected array $tlds;

	/**
	 * @param array<string, bool> $tlds   TLD-Hash-Set (ohne Punkt).
	 * @param int                 $points Punkte.
	 */
	public function __construct( array $tlds, int $points = self::DEFAULT_POINTS ) {
		parent::__construct( $points );
		$this->tlds = $tlds;
	}

	public function id(): string {
		return self::ID;
	}

	public function stage(): int {
		return 2;
	}

	public function evaluate( Context $context ): RuleResult {
		$hosts = Text::hosts( $context->field( 'content' ) );
		$extra = Text::host( $context->field( 'author_url' ) );
		if ( '' !== $extra ) {
			$hosts[] = $extra;
		}
		foreach ( $hosts as $host ) {
			$dot = strrpos( $host, '.' );
			if ( false === $dot ) {
				continue;
			}
			if ( isset( $this->tlds[ substr( $host, $dot + 1 ) ] ) ) {
				return $this->hit();
			}
		}
		return $this->miss();
	}
}
