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

namespace Hafenstudios\Wellenbrecher\Rules;

use Hafenstudios\Wellenbrecher\Db\CommentLookup;
use Hafenstudios\Wellenbrecher\Engine\Context;
use Hafenstudios\Wellenbrecher\Engine\RuleResult;

defined( 'ABSPATH' ) || exit;

/**
 * Kanal-Regel nach dem ASB-localdb-Muster (WB10): Autor-E-Mail, Autor-URL
 * oder IP matcht im Klartext einen vorhandenen Kommentar im nativen
 * WP-Spam-Ordner (comment_approved = 'spam'). Gilt nur fuer die
 * Kommentar-Kanaele; die W1-RepeatOffenderRule (IP-HMAC gegen hs_spam_log)
 * besteht unveraendert daneben.
 */
class CommentLocaldbRule extends AbstractRule {

	public const ID             = 'comment_localdb';
	public const DEFAULT_POINTS = 30;

	public const CHANNELS = array( 'comment', 'trackback', 'woo_review' );

	protected CommentLookup $lookup;

	/**
	 * @param CommentLookup $lookup Kommentar-Abfragen.
	 * @param int           $points Punkte.
	 */
	public function __construct( CommentLookup $lookup, int $points = self::DEFAULT_POINTS ) {
		parent::__construct( $points );
		$this->lookup = $lookup;
	}

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

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

	public function applies( Context $context ): bool {
		return in_array( $context->channel, self::CHANNELS, true );
	}

	public function evaluate( Context $context ): RuleResult {
		$match = $this->lookup->has_spam_match(
			$context->field( 'author_email' ),
			$context->field( 'author_url' ),
			$context->server( 'remote_addr' )
		);
		return $match ? $this->hit() : $this->miss();
	}
}
