#!perl
use Cassandane::Tiny;

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

    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',
    ];

    xlog $self, "Create Trash mailbox";
    $imap->create("Trash", "(USE (\\Trash))") || die;

    $res = $jmap->CallMethods([
        ['Mailbox/query', {
            sort => [{
                property => 'name',
            }],
        }, 'R1'],
        ['Mailbox/get', {
            '#ids' => {
                resultOf => 'R1',
                name => 'Mailbox/query',
                path => '/ids',
            },
            properties => ['name'],
        }, 'R2'],
    ], $using);
    $self->assert_num_equals(2, scalar @{$res->[0][1]{ids}});

    my $inboxId = $res->[0][1]{ids}[0];
    my $trashId = $res->[0][1]{ids}[1];

    xlog $self, "Create message in Inbox";
    $self->make_message('wantThisOne', body => 'blu blu');
    $self->{instance}->run_command({cyrus => 1}, 'squatter');
    $res = $jmap->CallMethods([
        ['Email/query', { }, 'R1'],
    ], $using);
    my $wantEmailId = $res->[0][1]{ids}[0];
    $self->assert_not_null($wantEmailId);

    xlog $self, "Create message that exists both in Trash and #jmap";
    my $admin = $self->{adminstore}->get_client();
    $jmap->Upload('someblob', "text/plain");
    $store->set_folder('Trash');
    $self->make_message('dontWantThisOne', body => 'blu blu');
    $admin->select('user.cassandane.Trash');
    $admin->copy('1', 'user.cassandane.#jmap');
    $self->{instance}->run_command({cyrus => 1}, 'squatter');

    xlog $self, "Query emails exluding Trash";
    $res = $jmap->CallMethods([
        ['Email/query', {
            filter => {
                operator => 'AND',
                conditions => [{
                    text => 'blu',
                }, {
                    inMailboxOtherThan => [$trashId],
                }],
            },
            sort => [
               {
                  "isAscending" => JSON::false,
                  "property" => "receivedAt"
               }
            ],
            disableGuidSearch => JSON::true,
        }, 'R1'],
    ], $using);

    xlog $self, "Assert that message from #jmap folder is not found";
    $self->assert_deep_equals([$wantEmailId], $res->[0][1]{ids});

}
