<?php

namespace Formatrica\Submission\Pipeline\Stages;

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

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

/**
 * User-registration forms take a different terminal path: register the user and
 * finish the pipeline with a registration result (no submission storage, email,
 * or integration dispatch).
 */
final class User_Registration_Stage implements Submission_Stage
{
    public function handle(Submission_Context $ctx): void
    {
        $form_type = $ctx->options['form_type'] ?? '';
        if ($form_type !== 'user_registration') {
            return;
        }

        $registration_handler = new User_Registration_Handler();
        $sanitised_with_opts = $ctx->sanitised;
        $sanitised_with_opts['__fmt_hporm_options'] = $ctx->options;
        $registration_result = $registration_handler->register_user($sanitised_with_opts);

        if (!$registration_result['success']) {
            throw new Submission_Exception(
                esc_html($registration_result['message']),
                400
            );
        }

        $ctx->finish([
            'success' => true,
            'message' => $registration_result['message'],
            'user_id' => $registration_result['user_id'],
        ]);
    }
}
