<?php

namespace Formatrica\Submission\Pipeline\Stages;

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

use Formatrica\Submission\Exception\Submission_Exception;
use Formatrica\Submission\Pipeline\Submission_Context;
use Formatrica\Submission\Pipeline\Submission_Stage;

/**
 * Abort with a 422 when the sanitised submission has field errors.
 */
final class Validation_Error_Stage implements Submission_Stage
{
    public function handle(Submission_Context $ctx): void
    {
        if (empty($ctx->errors)) {
            return;
        }

        $error_data = [
            'fields' => $ctx->errors,
            'data'   => $ctx->sanitised,
        ];

        throw new Submission_Exception(
            esc_html($ctx->options['error_message'] ?? __('Please check the highlighted fields.', 'formatrica')),
            422,
            $error_data // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- structured data for JSON response, not HTML output
        );
    }
}
