#!perl
use Cassandane::Tiny;

sub test_email_query_sieve_some_in_thread_have_keyword
    :needs_component_sieve :ConversationMaxThread10
{
    my ($self) = @_;
    my $jmap = $self->{jmap};
    my $imap = $self->{store}->get_client();

    xlog $self, "Set up Sieve script";
    $imap->create("matches") or die;
    my $sieve = <<EOF;
require ["x-cyrus-jmapquery", "x-cyrus-log", "variables", "fileinto"];
if
  allof( not string :is "\${stop}" "Y",
    jmapquery text:
    {
      "someInThreadHaveKeyword": "\$IsMailingList"
    }
.
  )
{
  fileinto "matches";
}
EOF
    $self->{instance}->install_sieve_script($sieve);

    xlog $self, "Create split conversation";
    my $messageId = 'messageid1@example.com';
    $self->make_message('Email A', messageid => $messageId);
    my $convMaxthread = $self->{instance}->{config}->get('conversations_max_thread');
    foreach (1 .. 2 * $convMaxthread - 1) {
        $self->make_message("Re: Email A",
            references => [ "<$messageId>" ],
        );
    }

    xlog $self, "Set flag on message in first conversation split";
    my $res = $imap->store($convMaxthread - 1, '+flags', '($IsMailingList)');

    my $mime = <<EOF;
From: helloworld\@local
To: to\@local
Subject: Re: Email A
References: <$messageId>
Date: Mon, 13 Apr 2020 15:34:03 +0200
MIME-Version: 1.0
Content-Type: text/plain;charset=us-ascii
Content-Transfer-Encoding: 7bit

hello
EOF
    $mime =~ s/\r?\n/\r\n/gs;
    my $msg = Cassandane::Message->new();
    $msg->set_lines(split /\n/, $mime);

    xlog $self, "Deliver message for conversation";
    $msg->remove_headers('Message-Id');
    $msg->set_headers('Message-Id', '<4bb20c19-3a9d-483f@local>');
    $self->{instance}->deliver($msg);

    xlog $self, "Assert that someInThreadHaveKeyword did not match";
    # XXX Might be OK to match here. But that's not how it is implemented.
    $self->assert_num_equals(0, $imap->message_count('matches'));

    xlog $self, "Set flag on message in second conversation split";
    $res = $imap->store($convMaxthread + 1, '+flags', '($IsMailingList)');

    xlog $self, "Deliver message for conversation";
    $msg->remove_headers('Message-Id');
    $msg->set_headers('Message-Id', '<ccda7f93-0328-47b8@local>');
    $self->{instance}->deliver($msg);

    xlog $self, "Assert that someInThreadHaveKeyword did match";
    $self->assert_num_equals(1, $imap->message_count('matches'));
}
