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

/**
 * Resolve request context (IP / user agent) and the IP formatted for storage.
 */
final class Build_Context_Stage implements Submission_Stage
{
    public function __construct(private IP_Handler $ip_handler)
    {
    }

    public function handle(Submission_Context $ctx): void
    {
        $context = $ctx->context;

        $ctx->context = [
            'ip_address' => isset($context['ip_address']) && is_string($context['ip_address'])
                ? $context['ip_address']
                : $this->ip_handler->detect(),
            'user_agent' => isset($context['user_agent']) && is_string($context['user_agent'])
                ? $context['user_agent']
                : (isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash((string) $_SERVER['HTTP_USER_AGENT'])) : ''),
        ];

        // Preserve the headless auth MARKERS set by the earlier Pro auth stage.
        // This stage runs after Headless_Auth_Stage but before Captcha_Stage,
        // which still consults 'headless_authenticated'; rebuilding the context
        // without these previously dropped the authenticated flag and wrongly
        // subjected a valid headless request to captcha. The API key itself is
        // deliberately NOT carried forward — it is scrubbed in Headless_Auth_Stage
        // so it can never reach webhooks, the integration queue, or hooks.
        foreach (['headless_requested', 'headless_authenticated'] as $marker) {
            if (isset($context[$marker])) {
                $ctx->context[$marker] = $context[$marker];
            }
        }

        $ip_storage_mode = $ctx->options['ip_storage'] ?? 'full';
        $ctx->stored_ip = $this->ip_handler->format_for_storage($ctx->context['ip_address'], $ip_storage_mode);
    }
}
