#!perl
use Cassandane::Tiny;

sub test_email_query_sort_category_matchnone
    :JMAPExtensions
    ($self)
{
    my $user = $self->default_user;
    my $jmap = $user->jmap;
    $jmap->AddUsing(
        'urn:ietf:params:jmap:contacts',
        'https://cyrusimap.org/ns/jmap/mail',
        'https://cyrusimap.org/ns/jmap/performance',
    );

    my $mboxa = $user->mailboxes->create({ name => 'A' });
    my $mboxb = $user->mailboxes->create({ name => 'B' });
    my $empty = $user->mailboxes->create({ name => 'Empty' });

    # The emails are created in the order below, which is also the order that
    # sorting by receivedAt ascending puts them in.
    my @emails = (
        { subject    => 'in_a',
          receivedAt => '2020-01-01T00:00:00Z',
          mailboxes  => [ $mboxa ] },
        { subject    => 'in_b',
          receivedAt => '2021-01-01T00:00:00Z',
          mailboxes  => [ $mboxb ] },
    );

    my %id_by_subject;
    for my $spec (@emails) {
        my $email = $user->emails->create({
            mailboxIds    => { map { $_->id => JSON::true }
                                   $spec->{mailboxes}->@* },
            from          => [ { email => 'sender@example.com' } ],
            subject       => $spec->{subject},
            receivedAt    => $spec->{receivedAt},
            bodyStructure => { type => 'text/plain', partId => 'part1' },
            bodyValues    => { part1 => { value => 'hello' } },
        });
        $id_by_subject{$spec->{subject}} = q{} . $email->id;
    }

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

    # A groupBy filter that can match no Email must leave its group empty,
    # not take every Email into it.
    my sub assert_grouping ($desc, $groupby, $want_subjects, $want_counts) {
        my $sort = [
            {
                property    => 'category',
                isAscending => JSON::true,
                groupBy     => $groupby,
            },
            {
                property    => 'receivedAt',
                isAscending => JSON::true,
            },
        ];

        # The body condition makes the query eligible for guidsearch
        my @methods;
        for my $impl (qw(guidsearch uidsearch)) {
            push @methods, [ 'Email/query', {
                filter            => { body => 'hello' },
                sort              => $sort,
                disableGuidSearch => $impl eq 'uidsearch'
                                        ? JSON::true : JSON::false,
            }, $impl ];
        }

        my $res = $jmap->request(\@methods);
        $res->assert_successful;

        my @want_ids = map { $id_by_subject{$_} } @$want_subjects;

        for my $impl (qw(guidsearch uidsearch)) {
            my $args = $res->paragraph_by_client_id($impl)
                           ->single('Email/query')->arguments;

            $self->assert_cmp_deeply(
                $impl eq 'guidsearch' ? jtrue() : jfalse(),
                $args->{performance}{details}{isGuidSearch},
                "$desc: isGuidSearch for $impl",
            );
            $self->assert_cmp_deeply(\@want_ids, $args->{ids},
                "$desc: ids for $impl");
            $self->assert_cmp_deeply($want_counts, $args->{groupByCounts},
                "$desc: groupByCounts for $impl");
        }
    }

    assert_grouping(
        'unknown contact card',
        [ { fromContactCardUid => 'no-such-card' } ],
        [ qw(in_a in_b) ],
        [ 0 ],
    );

    assert_grouping(
        'unknown contact card, then mailbox',
        [
            { fromContactCardUid => 'no-such-card' },
            { inMailbox => q{} . $mboxb->id },
        ],
        [ qw(in_b in_a) ],
        [ 0, 1 ],
    );

    assert_grouping(
        'empty mailbox, then mailbox',
        [
            { inMailbox => q{} . $empty->id },
            { inMailbox => q{} . $mboxb->id },
        ],
        [ qw(in_b in_a) ],
        [ 0, 1 ],
    );
}
