<?php
/**
 * Per-user rate limiting for Basic Forms AI requests.
 *
 * @package BasicForms
 */

namespace BasicForms;

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

final class AiRateLimiter {

	private const MAX_REQUESTS = 15;

	private const WINDOW_SECONDS = 60;

	public static function check(): bool|\WP_Error {
		$user_id = get_current_user_id();
		if ( $user_id <= 0 ) {
			return new \WP_Error( 'not_logged_in', __( 'You must be logged in to use AI features.', 'wp-powersuite' ) );
		}

		$key = 'wpps_bf_ai_rate_' . $user_id;

		// With an external object cache, get_transient()/set_transient() just
		// proxy to wp_cache_get()/wp_cache_set() on the 'transient' group, so
		// wp_cache_incr() on the same group/key is a real atomic increment
		// instead of a get-then-set race.
		if ( wp_using_ext_object_cache() ) {
			$count = wp_cache_get( $key, 'transient' );
			if ( $count === false ) {
				wp_cache_set( $key, 0, 'transient', self::WINDOW_SECONDS );
				$count = 0;
			}

			if ( (int) $count >= self::MAX_REQUESTS ) {
				return new \WP_Error(
					'rate_limit',
					__( 'Too many AI requests. Please wait a minute and try again.', 'wp-powersuite' )
				);
			}

			wp_cache_incr( $key, 1, 'transient' );

			return true;
		}

		$count = (int) get_transient( $key );

		if ( $count >= self::MAX_REQUESTS ) {
			return new \WP_Error(
				'rate_limit',
				__( 'Too many AI requests. Please wait a minute and try again.', 'wp-powersuite' )
			);
		}

		set_transient( $key, $count + 1, self::WINDOW_SECONDS );

		return true;
	}
}
