#!perl
use Cassandane::Tiny;

sub assert_email_querychanges_sortsavedate ($self, $sort_property,
                                            $collapse_threads)
{
    my $user = $self->default_user;
    my $jmap = $user->jmap;
    $jmap->AddUsing('https://cyrusimap.org/ns/jmap/mail');

    my $snoozed = $user->mailboxes->create({
        name => 'snoozed',
        role => 'snoozed',
    });

    # The snoozed#until of each email, in ascending order.  For a snoozed
    # email that is also its savedate, so both sorts see this order.
    my @snoozed_until = map {; sprintf '2042-01-%02dT00:00:00Z', $_ } 1..4;

    xlog $self, "Create four snoozed emails, each in its own thread";
    my (@emails, @ids);
    for my $i (0 .. $#snoozed_until) {
        my $email = $user->emails->create({
            mailboxIds    => { $snoozed->id => JSON::true },
            subject       => "snoozed email $i",
            snoozed       => { 'until' => $snoozed_until[$i] },
            bodyStructure => { type => 'text/plain', partId => 'part1' },
            bodyValues    => { part1 => { value => "email $i" } },
        });
        push @emails, $email;
        push @ids, q{} . $email->id;
    }

    my %query = (
        collapseThreads => $collapse_threads ? JSON::true : JSON::false,
        filter => { inMailbox => $snoozed->id },
        sort   => [ {
            isAscending => JSON::true,
            mailboxId   => $snoozed->id,
            property    => $sort_property,
        } ],
        calculateTotal => JSON::true,
    );

    xlog $self, "Query them by ascending $sort_property";
    my $res = $jmap->request([[ 'Email/query' => { %query } ]]);
    my $qres = $res->sentence_named('Email/query')->arguments;
    $self->assert_cmp_deeply(
        superhashof({
            canCalculateChanges => JSON::true,
            ids                 => \@ids,
            position            => 0,
            queryState          => jstr,
            total               => 4,
        }),
        $qres,
    );

    my $qstate = $qres->{queryState};

    xlog $self, "Re-snooze the first email to after the last one";
    $emails[0]->update({ 'snoozed/until' => '2042-01-05T00:00:00Z' });

    xlog $self, "The re-snoozed email is now last in the query";
    $res = $jmap->request([[ 'Email/query' => { %query } ]]);
    $self->assert_cmp_deeply(
        [ @ids[1,2,3], $ids[0] ],
        $res->sentence_named('Email/query')->arguments->{ids},
    );

    xlog $self, "Ask for changes, having cached up to the third position";
    $res = $jmap->request([[ 'Email/queryChanges' => {
        %query,
        sinceQueryState => $qstate,
        upToId          => $ids[2],
    } ]]);

    xlog $self, "The move past upToId must still be reported";
    $self->assert_cmp_deeply(
        superhashof({
            added   => [ { id => $ids[0], index => 3 } ],
            removed => [ $ids[0] ],
            total   => 4,
        }),
        $res->sentence_named('Email/queryChanges')->arguments,
    );
}

sub test_email_querychanges_sortsavedate__snoozeduntil
    :needs_component_sieve :JMAPExtensions
    ($self)
{
    $self->assert_email_querychanges_sortsavedate('snoozedUntil', 0);
}

sub test_email_querychanges_sortsavedate__snoozeduntil_collapsed
    :needs_component_sieve :JMAPExtensions
    ($self)
{
    $self->assert_email_querychanges_sortsavedate('snoozedUntil', 1);
}

sub test_email_querychanges_sortsavedate__addeddates
    :needs_component_sieve :JMAPExtensions
    ($self)
{
    $self->assert_email_querychanges_sortsavedate('addedDates', 0);
}

sub test_email_querychanges_sortsavedate__addeddates_collapsed
    :needs_component_sieve :JMAPExtensions
    ($self)
{
    $self->assert_email_querychanges_sortsavedate('addedDates', 1);
}
