#!perl
use Cassandane::Tiny;

sub test_mailbox_set_destroy_removemsgs
    :min_version_3_1
{
    my ($self) = @_;
    my $jmap = $self->{jmap};

    xlog "Create email in inbox and another mailbox";
    my $res = $jmap->CallMethods([
        ['Mailbox/query', { }, 'R1'],
        ['Mailbox/set', {
            create => {
                mbox => {
                    name => 'A',
                },
            },
        }, 'R2'],
        ['Email/set', {
            create => {
                email => {
                    mailboxIds => {
                        '$inbox' => JSON::true,
                        '#mbox' => JSON::true,
                    },
                    subject => 'email',
                    bodyStructure => {
                        type => 'text/plain',
                        partId => '1',
                    },
                    bodyValues => {
                        1 => {
                            value => 'email',
                        }
                    },
                },
            },
        }, 'R3'],
    ]);
    my $inboxId = $res->[0][1]{ids}[0];
    $self->assert_not_null($inboxId);
    my $mboxId = $res->[1][1]{created}{mbox}{id};
    $self->assert_not_null($mboxId);
    my $emailId = $res->[2][1]{created}{email}{id};
    $self->assert_not_null($emailId);

    $self->{instance}->getsyslog();

    xlog "Destroy mailbox with onDestroyRemoveEmails";
    $res = $jmap->CallMethods([
        ['Mailbox/set', {
            destroy => [$mboxId],
            onDestroyRemoveEmails => JSON::true,
        }, 'R1'],
        ['Email/get', {
            ids => [$emailId],
            properties => ['mailboxIds'],
        }, 'R2'],
    ]);
    $self->assert_deep_equals([$mboxId], $res->[0][1]{destroyed});
    $self->assert_deep_equals({ $inboxId => JSON::true },
        $res->[1][1]{list}[0]{mailboxIds});

    my ($maj, $min) = Cassandane::Instance->get_version();
    if ($maj > 3 || ($maj == 3 && $min >= 7)) {
        $self->assert_syslog_matches(
            $self->{instance},
            qr{Destroyed mailbox: mboxid=<$mboxId> msgcount=<1>}
        );
    }
}
