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

/**
 * Wegwerf-E-Mail-Domain (kuratierte CC0-Liste, gebundelt als Hash-Set).
 * Bei Registrierungen und Checkout ein starkes Signal (+25), bei
 * Blog-Kommentaren nur schwach (+10, dort faken Bots eher Gmail).
 */
class DisposableEmailRule extends AbstractRule {

	public const ID = 'disposable_email';

	public const DEFAULT_POINTS         = 25;
	public const DEFAULT_POINTS_COMMENT = 10;

	/**
	 * Kanaele mit dem starken Gewicht.
	 */
	public const STRICT_CHANNELS = array( 'registration', 'woo_checkout' );

	/**
	 * Disposable-Hash-Set (domain => true).
	 *
	 * @var array<string, bool>
	 */
	protected array $domains;

	protected int $points_comment;

	/**
	 * @param array<string, bool> $domains        Disposable-Hash-Set.
	 * @param int                 $points         Punkte Registrierung/Checkout.
	 * @param int                 $points_comment Punkte uebrige Kanaele.
	 */
	public function __construct( array $domains, int $points = self::DEFAULT_POINTS, int $points_comment = self::DEFAULT_POINTS_COMMENT ) {
		parent::__construct( $points );
		$this->domains        = $domains;
		$this->points_comment = $points_comment;
	}

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

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

	public function evaluate( Context $context ): RuleResult {
		$domain = Text::email_domain( $context->field( 'author_email' ) );
		if ( '' === $domain || ! isset( $this->domains[ $domain ] ) ) {
			return $this->miss();
		}
		$points = in_array( $context->channel, self::STRICT_CHANNELS, true ) ? $this->points : $this->points_comment;
		return new RuleResult( $points, $this->id() );
	}
}
