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

/**
 * Verify the configured CAPTCHA (when enabled) and strip its tokens from the
 * request payload before validation.
 */
final class Captcha_Stage implements Submission_Stage
{
    public function __construct(private Captcha_Service $captcha_service)
    {
    }

    public function handle(Submission_Context $ctx): void
    {
        // Authenticated headless API requests can't run a browser captcha; the
        // key auth + throttle are their gate. Skip only once authenticated (the
        // marker survives Build_Context_Stage), so an unverified request still
        // faces captcha.
        if (!empty($ctx->context['headless_authenticated'])) {
            return;
        }

        $captcha_config = $ctx->options['captcha'] ?? [];
        $captcha_provider = isset($captcha_config['provider']) && is_string($captcha_config['provider'])
            ? $captcha_config['provider']
            : 'none';

        if ($captcha_provider === 'none') {
            return;
        }

        $captcha_token = isset($ctx->request_data['_fmt_captcha_token']) ? trim((string) $ctx->request_data['_fmt_captcha_token']) : '';

        $this->captcha_service->verify($captcha_provider, $captcha_token, [
            'site_key' => $captcha_config['site_key'] ?? '',
            'secret_key' => $captcha_config['secret_key'] ?? '',
            'ip' => $ctx->context['ip_address'],
            'form_id' => $ctx->form_id,
        ]);

        unset(
            $ctx->request_data['_fmt_captcha_token'],
            $ctx->request_data['_fmt_captcha_provider'],
            $ctx->request_data['cf-turnstile-response'],
            $ctx->request_data['frc-captcha-response'],
            $ctx->request_data['frc-captcha-solution']
        );
    }
}
