#!perl
use Cassandane::Tiny;

sub test_email_bimi_blob_as_contact_avatar
    :min_version_3_5 :needs_component_sieve
    :JMAPExtensions
    ($self)
{
    my $jmap = $self->{jmap};

    # we need 'https://cyrusimap.org/ns/jmap/mail' capability for
    # bimiBlobId property
    my @using = @{ $jmap->DefaultUsing() };
    push @using, 'https://cyrusimap.org/ns/jmap/mail';
    push @using, 'https://cyrusimap.org/ns/jmap/contacts';
    push @using, 'urn:ietf:params:jmap:contacts';
    $jmap->DefaultUsing(\@using);

    my $binary = slurp_file(abs_path('data/FM_BIMI.svg'));
    my $b64 = encode_base64($binary, '');
    my $mtype = "image/svg+xml";

    $self->make_message("foo",
        mime_type => 'text/plain',
        extra_headers => [
            ['BIMI-Indicator', $b64]
        ],
        body => 'foo',
    ) || die;

    xlog $self, "get email list";
    my $res = $jmap->CallMethods([['Email/query', {}, "R1"]]);
    my $ids = $res->[0][1]->{ids};

    xlog $self, "get email";
    $res = $jmap->CallMethods([['Email/get', {
        ids => $ids,
        properties => ['bimiBlobId'],
    }, "R1"]]);
    my $msg = $res->[0][1]{list}[0];

    my $blobid = $msg->{bimiBlobId};
    $self->assert_not_null($blobid);

    my $blob = $jmap->Download({ accept => $mtype },
                               'cassandane', $blobid);
    $self->assert_str_equals($mtype, $blob->{headers}->{'content-type'});
    $self->assert_num_not_equals(0, $blob->{headers}->{'content-length'});
    $self->assert_equals($binary, $blob->{content});

    my $contact = {
        '@type' => 'Card',
        version => '1.0',
        name => { full => "foo" },
        media => {
            avatar => {
                kind => 'photo',
                uri => "data:" . $mtype . ";base64," . $b64
            }
        }
    };

    $res = $jmap->CallMethods([['ContactCard/set',
                                {create => {"1" => $contact }}, "R1"]]);
    $self->assert_not_null($res->[0][1]{created});
    $self->assert_not_null($res->[0][1]{created}{"1"}{media}{avatar}{blobId});
    $self->assert_str_equals($mtype,
                             $res->[0][1]{created}{"1"}{media}{avatar}{mediaType});
}
