#!perl
use Cassandane::Tiny;

sub test_mailbox_set_intermediary_destroy_child
    :min_version_3_1 :max_version_3_4 :NoAltNameSpace
{
    my ($self) = @_;

    my $jmap = $self->{jmap};
    my $imap = $self->{store}->get_client();

    xlog $self, "Create mailboxes";
    $imap->create("INBOX.i1.i2.foo") or die;
    my $res = $jmap->CallMethods([
        ['Mailbox/get', {
            properties => ['name', 'parentId'],
        }, "R1"]
    ]);
    my %mboxByName = map { $_->{name} => $_ } @{$res->[0][1]{list}};
    my $mboxIdFoo = $mboxByName{'foo'}->{id};
    my $mboxId1 = $mboxByName{'i1'}->{id};
    my $mboxId2 = $mboxByName{'i2'}->{id};
    my $state = $res->[0][1]{state};

    xlog $self, "Destroy child of intermediate";
    $res = $jmap->CallMethods([
        ['Mailbox/set', {
            destroy => [$mboxIdFoo],
        }, 'R1'],
    ]);
    $self->assert_str_equals($mboxIdFoo, $res->[0][1]{destroyed}[0]);
    $self->assert_str_not_equals($state, $res->[0][1]{newState});
    $state = $res->[0][1]{newState};

    xlog $self, "Assert mailbox tree and changes";
    $res = $jmap->CallMethods([
        ['Mailbox/get', {
            properties => ['name', 'parentId'],
        }, "R1"],
        ['Mailbox/changes', {
            sinceState => $state,
        }, 'R2'],
    ]);

    # All intermediaries without real children are gone.
    %mboxByName = map { $_->{name} => $_ } @{$res->[0][1]{list}};
    $self->assert_num_equals(1, scalar keys %mboxByName);
    $self->assert_not_null($mboxByName{'Inbox'});

    # But Mailbox/changes reports the implicitly destroyed mailboxes.
    $self->assert_num_equals(2, scalar @{$res->[1][1]{destroyed}});
    my %destroyed = map { $_ => 1 } @{$res->[1][1]{destroyed}};
    $self->assert_not_null($destroyed{$mboxId1});
    $self->assert_not_null($destroyed{$mboxId2});
}
