<?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;

/**
 * URL-Shortener-Domain im Inhalt oder in der Autor-URL: Spammer verstecken
 * Ziele hinter Kurz-URLs, legitime Kommentatoren so gut wie nie.
 */
class ShortenerRule extends AbstractRule {

	public const ID             = 'shortener';
	public const DEFAULT_POINTS = 15;

	/**
	 * Shortener-Hash-Set (host => true).
	 *
	 * @var array<string, bool>
	 */
	protected array $shorteners;

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

	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 ) {
			if ( isset( $this->shorteners[ $host ] ) ) {
				return $this->hit();
			}
		}
		return $this->miss();
	}
}
