#!perl
use Cassandane::Tiny;

sub test_using_annotstorage_msg_late
{
    my ($self) = @_;

    xlog $self, "test increasing usage of the X-ANNOTATION-STORAGE quota";
    xlog $self, "resource as per-message annotations are added";

    $self->_set_quotaroot('user.cassandane');
    my $talk = $self->{store}->get_client();

    $self->_check_no_quota();

    $talk->create("INBOX.sub1") || die "Failed to create subfolder";
    $talk->create("INBOX.sub2") || die "Failed to create subfolder";

    xlog $self, "make some messages to hang annotations on";
    my %expecteds = ();
    my $expected = 0;
    foreach my $folder ("INBOX", "INBOX.sub1", "INBOX.sub2")
    {
        $self->{store}->set_folder($folder);
        $expecteds{$folder} = 0;
        my $uid = 1;
        for (1..5)
        {
            $self->make_message("Message $uid");

            my $data = $self->make_random_data(10);
            $talk->store('' . $uid, 'annotation', ['/comment', ['value.priv', { Quote => $data }]]);
            $self->assert_str_equals('ok', $talk->get_last_completion_response());
            $uid++;
            $expecteds{$folder} += length($data);
            $expected += length($data);
        }
    }

    $self->_set_limits($self->res_annot_storage => 100000);
    $self->_check_usages($self->res_annot_storage => int($expected/1024));

    xlog $self, "delete subfolder sub1";
    $talk->delete("INBOX.sub1") || die "Failed to delete subfolder";
    $expected -= delete($expecteds{"INBOX.sub1"});
    $self->_check_usages($self->res_annot_storage => int($expected/1024));

    xlog $self, "delete messages in sub2";
    $talk->select("INBOX.sub2");
    $talk->store('1:*', '+flags', '(\\deleted)');
    $self->assert_str_equals('ok', $talk->get_last_completion_response());
    $talk->expunge();

    xlog $self, "X-ANNOTATION-STORAGE quota goes down immediately";
    $expected -= delete($expecteds{"INBOX.sub2"});
    $self->_check_usages($self->res_annot_storage => int($expected/1024));

    $self->run_delayed_expunge();
    $talk = $self->{store}->get_client();

    xlog $self, "X-ANNOTATION-STORAGE quota should have been unchanged by expunge";
    $self->_check_usages($self->res_annot_storage => int($expected/1024));

    xlog $self, "delete annotations on INBOX";
    $talk->select("INBOX");
    $talk->store('1:*', 'annotation', ['/comment', ['value.priv', undef]]);
    $self->assert_str_equals('ok', $talk->get_last_completion_response());
    $expected -= delete($expecteds{"INBOX"});
    $self->assert_num_equals(0, $expected);
    $self->_check_usages($self->res_annot_storage => int($expected/1024));
}
