#!perl
use Cassandane::Tiny;

# A replica which was behind when master expunged and repacked a message
# never sees the expunged record, so it must inherit master's
# deletedmodseq rather than answering Email/changes from its own.

sub test_email_changes_replica_behind_cannot_calculate_changes
    :needs_component_jmap :needs_component_replication :Replication
    :NoReplicaonly
    ($self)
{
    my $master_jmap = $self->default_user->jmap;

    xlog $self, "deliver message to master";
    $self->make_message("Message X") or die;

    my $email_id = $master_jmap->request(
        [['Email/query', {} ]])->single_sentence->arguments->{ids}[0];
    $self->assert_not_null($email_id);

    xlog $self, "replicate master -> replica";
    $self->run_replication();
    $self->check_replication('cassandane');

    xlog $self, "get Email state from replica";
    my $replica_jmap = $self->{replica}->new_jmaptester_for_user($self->default_user);
    my $res = $replica_jmap->request(
        [['Email/get', { ids => [$email_id], properties => ['id'] } ]]);
    $self->assert_str_equals($email_id, $res->single_sentence->arguments->{list}[0]{id});

    my $email_state = $replica_jmap->request(
        [['Email/get', { ids => [] } ]])->single_sentence->arguments->{state};
    $self->assert_not_null($email_state);

    xlog $self, "destroy Email on master";
    $res = $master_jmap->request([[ 'Email/set', { destroy => [$email_id] } ]]);
    $self->assert_cmp_deeply([$email_id],
                              $res->single_sentence->arguments->{destroyed});

    xlog $self, "expunge the record on master, without replicating first";
    $self->run_delayed_expunge();

    xlog $self, "assert that master returns cannotCalculateChanges";
    $res = $master_jmap->request([[ 'Email/changes', {
        sinceState  => $email_state,
        includeCADs => jtrue,
    } ]]);
    $self->assert_str_equals("cannotCalculateChanges",
                             $res->single_sentence->arguments->{type} // '');

    xlog $self, "replicate onto the stale replica";
    $self->run_replication();
    $self->check_replication('cassandane');

    xlog $self, "call Email/changes on the replica";
    $replica_jmap = $self->{replica}->new_jmaptester_for_user($self->default_user);
    $res = $replica_jmap->request([[ 'Email/changes', {
        sinceState  => $email_state,
        includeCADs => jtrue,
    } ]]);

    xlog $self, "assert that replica returns cannotCalculateChanges";
    $self->assert_str_equals('error', $res->single_sentence->name);
    $self->assert_str_equals('cannotCalculateChanges',
                             $res->single_sentence->arguments->{type});
}
