<%ARGS>
$ARGSRef => {}
</%ARGS>
<%INIT>
my ( $is_create, $is_update );
if ( ( $ARGSRef->{id} || '' ) eq 'new' ) {
    my $queue = RT::Queue->new( $session{CurrentUser} );
    $queue->Load( $ARGSRef->{Queue} );
    return unless $queue->id;

    return if $queue->CurrentUserHasRight('NoCaptchaOnCreate');
    $is_create = 1;
}
elsif ( $ARGSRef->{UpdateContent} ) {
    my $ticket = LoadTicket( $ARGSRef->{id} );
    return if $ticket->CurrentUserHasRight('NoCaptchaOnUpdate');
    $is_update = 1;
}
else {
    return;
}

if ( my $token = $ARGSRef->{'g-recaptcha-response'} ) {
    require Captcha::reCAPTCHA::V3;
    my $rc = Captcha::reCAPTCHA::V3->new(
        sitekey => RT->Config->Get('CaptchaSiteKey') || '',
        secret  => RT->Config->Get('CaptchaSecret') || '',
    );

    my $verify = $rc->verify($token);

    RT->Logger->debug("User " .$session{CurrentUser}->Name . " captcha verification score: $verify->{score}.");

    my $score = RT->Config->Get('CaptchaScore') || 0.5;

    return if $verify->{score} >= $score;

    RT->Logger->warning("User " .$session{CurrentUser}->Name . " failed captcha verification. Score $verify->{score} was below $score.");
}

my $key     = Digest::MD5::md5_hex( rand(1024) );
my $actions = $session{Actions}->{$key} || [];

push @$actions, loc("This site uses Google reCaptcha and your user verification failed. You can try again or try in a different browser.");
RT::Interface::Web::Session::Set(
    Key    => 'Actions',
    SubKey => $key,
    Value  => $actions,
);

my $page  = $is_create ? 'Create.html' : 'Update.html';
my $param = $is_create ? 'Queue' : 'id';
my $url   = RT->Config->Get('WebURL')
    . "Ticket/$page?$param="
    . $m->interp->apply_escapes( $ARGSRef->{$param}, 'u' )
    . "&results=$key";
RT::Interface::Web::Redirect($url);
</%INIT>
