#!perl
use Cassandane::Tiny;

sub test_email_parse_embedded_toplevel
    :min_version_3_3 :needs_component_sieve
{
    my ($self) = @_;
    my $jmap = $self->{jmap};

    my $res = $jmap->CallMethods([
        ['Email/set', {
            create => {
                1 => {
                    mailboxIds => {
                        '$inbox' => JSON::true,
                    },
                    subject => 'test1',
                    bodyStructure => {
                        type => 'text/plain',
                        partId => 'part1',
                    },
                    bodyValues => {
                        part1 => {
                            value => 'A text body',
                        },
                    },
                },
            },
        }, 'R1'],
    ]);
    my $blobId = $res->[0][1]{created}{1}{blobId};
    $self->assert_not_null($blobId);

    $res = $jmap->CallMethods([
        ['Email/set', {
            create => {
                2 => {
                    mailboxIds => {
                        '$inbox' => JSON::true,
                    },
                    subject => 'test2',
                    bodyStructure => {
                        subParts => [{
                            type => 'text/plain',
                            partId => 'part1',
                        }, {
                            type => 'message/rfc822',
                            blobId => $blobId,
                        }],
                    },
                    bodyValues => {
                        part1 => {
                            value => 'A text body',
                        },
                    },
                },
            },
        }, 'R1'],
        ['Email/get', {
            ids => ['#2'],
            properties => ['bodyStructure'],
            bodyProperties => ['blobId'],
        }, 'R2'],
    ]);
    $self->assert_not_null($res->[0][1]{created}{2});
    $self->assert_str_equals($blobId,
        $res->[1][1]{list}[0]{bodyStructure}{subParts}[1]{blobId});

    $res = $jmap->CallMethods([
        ['Email/parse', {
            blobIds => [ $blobId ],
            properties => ['blobId'],
        }, 'R1'],
    ]);
    $self->assert_str_equals($blobId, $res->[0][1]{parsed}{$blobId}{blobId});
}
