#!perl
use Cassandane::Tiny;

sub test_email_query_highpriority
    :min_version_3_3 :needs_component_sieve :needs_component_jmap
    :JMAPExtensions
{
    my ($self) = @_;
    my $jmap = $self->{jmap};
    my $imap = $self->{store}->get_client();

    xlog "Append emails with and without priority";
    $self->make_message("msg1",
        extra_headers => [['x-priority', '1']],
        body => "msg1"
    ) || die;
    $self->make_message("msg2",
        extra_headers => [['importance', 'high']],
        body => "msg2"
    ) || die;
    $self->make_message("msg3",
        body => "msg3"
    ) || die;

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

    my $using = [
        'urn:ietf:params:jmap:core',
        'urn:ietf:params:jmap:mail',
        'urn:ietf:params:jmap:submission',
        'https://cyrusimap.org/ns/jmap/mail',
        'https://cyrusimap.org/ns/jmap/debug',
        'https://cyrusimap.org/ns/jmap/performance',
    ];

    my $res = $jmap->CallMethods([
        ['Email/query', {
            sort => [{
                property => 'subject',
            }],
        }, 'R1'],
    ], $using);
    my @ids = @{$res->[0][1]{ids}};
    $self->assert_num_equals(3, scalar @ids);

    xlog "Query isHighPriority";
    $res = $jmap->CallMethods([
        ['Email/query', {
            filter => {
                isHighPriority => JSON::true,
            },
            sort => [{
                property => 'subject',
            }],
        }, 'R1'],
        ['Email/query', {
            filter => {
                operator => 'NOT',
                conditions => [{
                    isHighPriority => JSON::true,
                }],
            },
            sort => [{
                property => 'subject',
            }],
        }, 'R2'],
        ['Email/query', {
            filter => {
                isHighPriority => JSON::false,
            },
            sort => [{
                property => 'subject',
            }],
        }, 'R3'],
    ], $using);
    $self->assert_deep_equals([$ids[0], $ids[1]], $res->[0][1]{ids});
    $self->assert_deep_equals([$ids[2]], $res->[1][1]{ids});
    $self->assert_deep_equals([$ids[2]], $res->[2][1]{ids});
}
