<?php
/**
 * Light rate limit for OAuth callback (transient, per-IP).
 *
 * @package WP_PowerSuite\OAuth\Helpers
 */

namespace WP_PowerSuite\OAuth\Helpers;

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

final class RateLimiter {

	private const RATE_KEY_PREFIX = 'wpps_oauth_rl_';
	private const MAX_ATTEMPTS    = 30;
	private const WINDOW          = 600; // 10 minutes.

	public static function allow( string $context = 'callback' ): bool {
		$ip = self::clientIp();
		if ( $ip === '' ) {
			return true;
		}
		$key   = self::RATE_KEY_PREFIX . $context . '_' . md5( $ip );
		$count = (int) get_transient( $key );
		if ( $count > self::MAX_ATTEMPTS ) {
			return false;
		}
		set_transient( $key, $count + 1, self::WINDOW );
		return true;
	}

	private static function clientIp(): string {
		if ( class_exists( \WP_PowerSuite\Captcha\Shared\ClientIp::class ) ) {
			return (string) \WP_PowerSuite\Captcha\Shared\ClientIp::resolve();
		}
		$ip = $_SERVER['REMOTE_ADDR'] ?? '';
		return is_string( $ip ) ? sanitize_text_field( $ip ) : '';
	}
}
