#!perl
use Cassandane::Tiny;

# check that seen flags are set correctly on body fetch
# even if the flag was removed in the same session
sub test_setseen_after_store ($self)
{
    # need to version-gate IMAP features that aren't in 3.9...
    my ($maj, $min) = Cassandane::Instance->get_version();

    my $talk = $self->{store}->get_client();
    $self->{store}->_select();
    $self->assert_num_equals(1, $talk->uid());
    $self->{store}->set_fetch_attributes(qw(uid flags));

    xlog $self, "Add two messages";
    my %msg;
    $msg{A} = $self->make_message('Message A');
    $msg{A}->set_attributes(id => 1,
                            uid => 1,
                            flags => []);
    $msg{B} = $self->make_message('Message B');
    $msg{B}->set_attributes(id => 2,
                            uid => 2,
                            flags => []);
    $self->check_messages(\%msg);

    xlog $self, "Fetch body of message A";
    $talk->fetch('1', '(body[])');
    $msg{A}->set_attribute(flags => ['\\Seen']);
    $self->check_messages(\%msg);

    xlog $self, "Fetch remove the flag again, and immediately fetch the body";
    my $res = $talk->store('1', '-flags.silent', "(\\Seen)");
    if ($maj > 3 || ($maj == 3 && $min >= 9)) {
       $self->assert_deep_equals({}, $res);
    }
    else {
       # XXX flags.silent should cause there to not be an untagged response
       # XXX unless the affected data was also modified by another user, but
       # XXX for some reason Cyrus still returns it here?
       $self->assert_deep_equals({ '1' => { 'flags' => [] }}, $res);
    }
    $talk->fetch('1', '(body[])');
    $self->check_messages(\%msg);

    xlog $self, "Reconnect, \\Seen should still be on message A";
    $self->{store}->disconnect();
    $self->{store}->connect();
    $self->{store}->_select();
    $self->check_messages(\%msg);
}
