#!perl
use Cassandane::Tiny;

# When copying from account A to B, we should treat the write to B like an
# append: it must not cause B to exceed its quota usage.
sub test_email_copy_quota_storage
    :min_version_3_1
{
    my ($self) = @_;

    my $jmap = $self->{jmap};
    my $admintalk = $self->{adminstore}->get_client();

    xlog $self, "Tighten cassandane's storage quota to 1 KiB";
    $self->_set_quotaroot('user.cassandane');
    $self->_set_quotalimits(storage => 1);  # 1 * 1024 bytes

    xlog $self, "Create other and grant cassandane read on their INBOX";
    $self->{instance}->create_user('other');
    $admintalk->setacl('user.other', cassandane => 'lrswipkxtecdn') or die;

    xlog $self, "Land a >1 KiB message in other's INBOX";
    my $otherstore = $self->{instance}->get_service('imap')
                                      ->create_store(username => 'other');
    $self->make_message('too big to copy',
                        body => 'X' x 4096,   # more than the 1 KiB quota!
                        store => $otherstore) or die;

    xlog $self, "Find the message in other's account, and cassandane's INBOX";
    my $res = $jmap->CallMethods([
        ['Email/query', { accountId => 'other' }, 'R1'],
        ['Mailbox/get', { properties => ['name', 'role'] }, 'R2'],
    ]);
    my $emailid = $res->[0][1]{ids}[0];
    $self->assert_not_null($emailid);

    my ($inbox) = grep {; ($_->{role} // '') eq 'inbox' }
                  @{ $res->[1][1]{list} };
    my $cass_inbox_id = $inbox->{id};
    $self->assert_not_null($cass_inbox_id);

    xlog $self, "Email/copy from other -> cassandane (over quota)";
    $res = $jmap->CallMethods([
        ['Email/copy', {
            fromAccountId => 'other',
            accountId => 'cassandane',
            create => {
                copy => {
                    id => $emailid,
                    mailboxIds => {
                        $cass_inbox_id => JSON::true,
                    },
                },
            },
        }, 'R1'],
    ]);

    xlog $self, "can't copy email, get overQuota";
    $self->assert_null($res->[0][1]{created}{copy});
    $self->assert_str_equals('overQuota',
                             $res->[0][1]{notCreated}{copy}{type});
}
