#!perl
use Cassandane::Tiny;

sub test_email_query_sort_category_legacy_index
    :JMAPExtensions
    ($self)
{
    # Message-Id, References and In-Reply-To only got indexed in Xapian
    # databases of version 17 and higher. A filter falls back to reading
    # them from the message cache, a category sort has no such fallback.

    my $user = $self->default_user;
    my $jmap = $user->jmap;
    $jmap->AddUsing('https://cyrusimap.org/ns/jmap/mail');

    my $imap = $self->{store}->get_client();
    $imap->append('INBOX', to_crlf(<<'EOF')) || die $@;
From: from@local
To: to@local
Message-ID: <foo@example.com>
Subject: test
Date: Mon, 13 Apr 2020 15:34:03 +0200
MIME-Version: 1.0
Content-Type: text/plain

test
EOF

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

    my sub group_by_messageid () {
        return $jmap->request([[ 'Email/query', {
            sort => [ {
                property => 'category',
                groupBy  => [ { messageId => 'foo@example.com' } ],
            } ],
        }, 'R1' ]]);
    }

    my $res = group_by_messageid();
    $res->assert_successful;
    $self->assert_cmp_deeply([ 1 ],
        $res->single_sentence('Email/query')->arguments->{groupByCounts},
        'groupByCounts');

    xlog $self, 'downgrade the index to a version without message-ids';

    my $xapdirs = ($self->{instance}->run_mbpath(-u => 'cassandane'))->{xapian};
    $self->{instance}->run_command({}, 'xapian-metadata', 'set',
        $xapdirs->{t1} . '/xapian', 'cyrus.db_version', '16');

    $self->assert_cmp_deeply(superhashof({
        type => 'unsupportedSort',
        sort => [ 'sort[0]' ],
    }), group_by_messageid()->single_sentence('error')->arguments,
        'unsupported sort');

    $self->assert_syslog_matches($self->{instance},
        qr/event=jmap\.email\.query\.index_too_old/);
}
