#!perl
use Cassandane::Tiny;

sub test_jmapquery_index_levels
    :needs_component_jmap :SearchAttachmentExtractor :JMAPExtensions
    ($self)
{
    my $imap = $self->{store}->get_client();
    my $instance = $self->{instance};

    my $uri = URI->new($instance->{config}->get('search_attachment_extractor_url'));
    my $handler = sub ($conn, $req) {
        my $res = HTTP::Response->new($req->method eq 'HEAD' ? 204 : 200);
        $res->content($req->method eq 'HEAD' ? "" : "testattach");
        $conn->send_response($res);
    };
    $instance->start_httpd($handler, $uri->port());

    my @folders = qw(header nobody notbody body text attachbody);
    $imap->create("INBOX.$_") or die for @folders;

    # Each filter needs at least as deep an index as the one before it.
    $instance->install_sieve_script(<<'EOF'
require ["x-cyrus-jmapquery", "fileinto", "copy"];
if jmapquery text:
  { "from": "from@local" }
.
{ fileinto :copy "INBOX.header"; }
if jmapquery text:
  { "body": "nosuchword" }
.
{ fileinto :copy "INBOX.nobody"; }
if jmapquery text:
  { "operator": "NOT", "conditions": [ { "body": "testbody" } ] }
.
{ fileinto :copy "INBOX.notbody"; }
if jmapquery text:
  { "body": "testbody" }
.
{ fileinto :copy "INBOX.body"; }
if jmapquery text:
  { "text": "testattach" }
.
{ fileinto :copy "INBOX.text"; }
if jmapquery text:
  { "attachmentBody": "testattach" }
.
{ fileinto :copy "INBOX.attachbody"; }
EOF
    );

    my $mime = to_crlf(<<'EOF');
From: from@local
To: to@local
Subject: testsubject
Date: Mon, 13 Apr 2020 15:34:03 +0200
MIME-Version: 1.0
Content-Type: multipart/mixed;
 boundary=c4683f7a320d4d20902b000486fbdf9b

--c4683f7a320d4d20902b000486fbdf9b
Content-Type: text/plain

testbody

--c4683f7a320d4d20902b000486fbdf9b
Content-Disposition: attachment;filename="test.pdf"
Content-Type: application/pdf; name="test.pdf"
Content-Transfer-Encoding: base64

dGVzdGF0dGFjaG1lbnQK

--c4683f7a320d4d20902b000486fbdf9b--
EOF

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

    my %got;
    for my $folder (@folders) {
        $imap->select("INBOX.$folder");
        $got{$folder} = $imap->get_response_code('exists');
    }
    $self->assert_cmp_deeply({
        header => 1,
        nobody => 0,
        notbody => 0,
        body => 1,
        text => 1,
        attachbody => 1,
    }, \%got);
}
