#!perl
use Cassandane::Tiny;

sub test_jmapquery_attachmentindexing_text
    :min_version_3_9 :needs_component_jmap
    :SearchAttachmentExtractor :JMAPExtensions
{
    # Assert that a 'text' filter in a Sieve script DOES
    # cause the attachment indexer to get called.

    my ($self) = @_;
    my $jmap = $self->{jmap};
    my $imap = $self->{store}->get_client();
    my $instance = $self->{instance};

    my $uri = URI->new($instance->{config}->get('search_attachment_extractor_url'));

    # Start a dummy extractor server.
    my $handler = sub {
        my ($conn, $req) = @_;
        if ($req->method eq 'HEAD') {
            my $res = HTTP::Response->new(204);
            $res->content("");
            $conn->send_response($res);
        } else {
            my $res = HTTP::Response->new(200);
            $res->content("testattach");
            $conn->send_response($res);
        }
    };
    $instance->start_httpd($handler, $uri->port());

    $imap->create("matches") or die;

    $self->{instance}->install_sieve_script(<<'EOF'
require ["x-cyrus-jmapquery", "x-cyrus-log", "variables", "fileinto"];
if
  allof( not string :is "${stop}" "Y",
    jmapquery text:
  {
    "body": "testbody"
  }
.
,
    jmapquery text:
  {
    "text": "testattach"
  }
.
,
    jmapquery text:
  {
    "attachmentBody": "testattach"
  }
.
  )
{
  fileinto "matches";
}
EOF
    );

    my $mime = <<'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
    $mime =~ s/\r?\n/\r\n/gs;

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

    xlog "Assert that message got moved into INBOX.matches";
    $imap->select('matches');
    $self->assert_num_equals(1, $imap->get_response_code('exists'));
    $imap->unselect();
}
