<?php

namespace Formatrica\Submission\Pipeline\Stages;

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

use Formatrica\Submission\Pipeline\Submission_Context;
use Formatrica\Submission\Pipeline\Submission_Stage;
use Formatrica\Submission\Security\Rate_Limiter;

/**
 * Per-form/IP rate limiting.
 */
final class Rate_Limit_Stage implements Submission_Stage
{
    public function __construct(private Rate_Limiter $rate_limiter)
    {
    }

    public function handle(Submission_Context $ctx): void
    {
        $throttle = $ctx->options['throttle'] ?? [];
        $max_requests = max(1, (int) ($throttle['max_requests'] ?? 3));
        $per_seconds = max(1, (int) ($throttle['per_seconds'] ?? 10));

        $this->rate_limiter->enforce($ctx->form_id, $ctx->context['ip_address'], $max_requests, $per_seconds);
    }
}
