#!perl
use Cassandane::Tiny;
use Encode qw(decode encode);
use JSON qw(encode_json);

sub test_email_query_utf8punct_term
    :needs_component_sieve :JMAPExtensions
{
    my ($self) = @_;
    my $jmap = $self->{jmap};
    my $imap = $self->{store}->get_client();
    $jmap->AddUsing('https://cyrusimap.org/ns/jmap/performance');
    $jmap->AddUsing('https://cyrusimap.org/ns/jmap/debug');
    $jmap->AddUsing('https://cyrusimap.org/ns/jmap/mail');

    xlog $self, "Create MIME message containing a non-ASCII punctuation char";
    my $mime = <<"EOF";
From: <from\@local>
To: <to\@local>
Subject: test
Date: Mon, 13 Apr 2020 15:34:03 +0200
MIME-Version: 1.0
Content-Transfer-Encoding: 8BIT
Content-Type: text/plain; charset=utf-8

hello \N{U+2013} world
EOF
    $mime =~ s/\r?\n/\r\n/gs;
    $mime = encode('utf-8', $mime);
    $imap->append('INBOX', $mime) || die $@;

    xlog $self, "run squatter";
    $self->{instance}->run_command({cyrus => 1}, 'squatter');

    my $filter = {
        operator => 'AND',
        conditions => [{
            body => 'hello'
        }, {
            body => "\N{U+2013}",
        }, {
            body => 'world',
        }],
    };

    xlog $self, "Assert Email/query ignores punctuation character in filter";
    my $res = $jmap->CallMethods([
        ['Email/query', {
            filter => $filter,
            disableGuidSearch => JSON::true,
        }, 'R1'],
        ['Email/query', {
            filter => $filter,
        }, 'R2'],
    ]);
    $self->assert_equals(JSON::false,
        $res->[0][1]{performance}{details}{isGuidSearch});
    $self->assert_num_equals(1, scalar @{$res->[0][1]{ids}});
    $self->assert_equals(JSON::true,
        $res->[1][1]{performance}{details}{isGuidSearch});
    $self->assert_num_equals(1, scalar @{$res->[1][1]{ids}});

    xlog $self, "Assert JMAP Sieve ignores punctuation character in filter";
    $imap->create("matches") or die;
    my $filterAsStr = encode_json($filter);
    $self->{instance}->install_sieve_script(<<"EOF"
require ["x-cyrus-jmapquery", "x-cyrus-log", "variables", "fileinto"];
if
  allof( not string :is "\${stop}" "Y",
    jmapquery text:
  $filterAsStr
.
  )
{
  fileinto "matches";
}
EOF
    );

    my $msg = Cassandane::Message->new();
    $msg->set_lines(split /\n/, $mime);
    $self->{instance}->deliver($msg);

    $imap->select('matches');
    $self->assert_num_equals(1, $imap->get_response_code('exists'));
    $imap->unselect();
}
