<?php
/**
 * Answyr — Rate limiter.
 *
 * Per-key sliding window backed by transients. Used to throttle public intake
 * (form submissions / chat) and AI calls. Ported from SimplyChat.
 *
 * @package Answyr
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class Answyr_Rate_Limiter {

	/**
	 * @param string $key    Caller identity (e.g. "intake_" . hashed IP).
	 * @param int    $limit  Max events per window.
	 * @param int    $window Window length in seconds.
	 */
	public static function allow( string $key, int $limit = 20, int $window = HOUR_IN_SECONDS ): bool {
		$transient = 'answyr_rl_' . md5( $key );
		$count     = (int) get_transient( $transient );

		if ( $count >= $limit ) {
			return false;
		}

		set_transient( $transient, $count + 1, $window );
		return true;
	}

	/** Identify an anonymous caller by hashed IP (privacy-preserving). */
	public static function client_key( string $scope ): string {
		$ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : 'unknown';
		return $scope . '_' . wp_hash( $ip );
	}
}
