#!perl
use Cassandane::Tiny;

sub test_email_query_header
    :min_version_3_5 :needs_component_sieve :needs_component_jmap
    :JMAPExtensions :NoMunge8Bit :RFC2047_UTF8
{
    my ($self) = @_;
    my $jmap = $self->{jmap};
    my $imap = $self->{store}->get_client();

use utf8;

    $self->make_message("xhdr1",
        extra_headers => [['X-hdr', 'val1'], ['X-hdr', 'val2']],
        body => "xhdr1"
    ) || die;
    $self->make_message("xhdr2",
        extra_headers => [['X-hdr', 'val1']],
        body => "xhdr2"
    ) || die;
    $self->make_message("xhdr3",
        extra_headers => [['X-hdr', " s\xc3\xa4ge   "]],
        body => "xhdr3"
    ) || die;
    $self->make_message("subject1",
        body => "subject1"
    ) || die;

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

    my $res = $jmap->CallMethods([
        ['Email/query', {
        }, 'R1'],
        ['Email/get', {
            '#ids' => {
                resultOf => 'R1',
                name => 'Email/query',
                path => '/ids'
            },
            properties => [ 'subject' ],
        }, 'R2'],
    ]);
    my %id = map { $_->{subject} => $_->{id} } @{$res->[1][1]{list}};

    my @testCases = ({
        desc => 'xhdr equals',
        header => ['x-hdr', 'val2', 'equals'],
        wantIds => [$id{'xhdr1'}],
    }, {
        desc => 'xhdr startsWith',
        header => ['x-hdr', 'val', 'startsWith'],
        wantIds => [$id{'xhdr1'}, $id{'xhdr2'}],
    }, {
        desc => 'xhdr endsWith',
        header => ['x-hdr', 'al1', 'endsWith'],
        wantIds => [$id{'xhdr1'}, $id{'xhdr2'}],
    }, {
        desc => 'xhdr contains',
        header => ['x-hdr', 'al', 'contains'],
        wantIds => [$id{'xhdr1'}, $id{'xhdr2'}],
    }, {
        desc => 'xhdr contains utf8 value',
        header => ['x-hdr', 'SaGE', 'contains'],
        wantIds => [$id{'xhdr3'}],
    }, {
        desc => 'subject contains ASCII',
        header => ['subject', 'ubjec', 'contains'],
        wantIds => [$id{'subject1'}],
    });

    foreach (@testCases) {
        xlog "Running test: $_->{desc}";
        $res = $jmap->CallMethods([
            ['Email/query', {
                filter => {
                    header => $_->{header},
                },
                sort => [{ property => 'subject' }],
            }, 'R1'],
        ]);
        $self->assert_deep_equals($_->{wantIds}, $res->[0][1]{ids});
    }

no utf8;
}
