#!perl
use Cassandane::Tiny;

sub test_blob_lookup
    :min_version_3_5 :needs_component_jmap :JMAPExtensions
{
    my $self = shift;
    my $jmap = $self->{jmap};

    my $store = $self->{store};
    my $talk = $store->get_client();
    my $inbox = 'INBOX';

    xlog $self, "Generate an email in $inbox via IMAP";
    my %exp_sub;
    $store->set_folder($inbox);
    $store->_select();
    $self->{gen}->set_next_uid(1);

    my $body = "A plain text email.";
    $exp_sub{A} = $self->make_message("foo",
        body => $body
    );

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

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

    my $blobId = $msg->{textBody}[0]{blobId};
    $self->assert_not_null($blobId);
    my $emailId = $msg->{id};
    $self->assert_not_null($emailId);
    my $threadId = $msg->{threadId};
    $self->assert_not_null($threadId);
    my $mailboxIds = $msg->{mailboxIds};
    my ($mailboxId) = keys %$mailboxIds;
    $self->assert_not_null($mailboxId);

    xlog "Test without capability";
    $res = $jmap->CallMethods([['Blob/lookup', { ids => [$blobId, 'unknown'], typeNames => ['Mailbox', 'Thread', 'Email'] }, 'R1']]);
    $self->assert_str_equals($res->[0][0], 'error');

    # XXX: this will be replaced with the upstream one
    $jmap->AddUsing('https://cyrusimap.org/ns/jmap/blob');

    xlog "Regular Blob/lookup works";
    $res = $jmap->CallMethods([['Blob/lookup', { ids => [$blobId, 'unknown'], typeNames => ['Mailbox', 'Thread', 'Email'] }, 'R1']]);
    $self->assert_str_equals($res->[0][0], 'Blob/lookup');
    $self->assert_num_equals(1, scalar @{$res->[0][1]{list}});
    $self->assert_str_equals($blobId, $res->[0][1]{list}[0]{id});
    $self->assert_num_equals(1, scalar @{$res->[0][1]{list}[0]{matchedIds}{Mailbox}});
    $self->assert_str_equals($mailboxId, $res->[0][1]{list}[0]{matchedIds}{Mailbox}[0]);
    $self->assert_num_equals(1, scalar @{$res->[0][1]{list}[0]{matchedIds}{Thread}});
    $self->assert_str_equals($threadId, $res->[0][1]{list}[0]{matchedIds}{Thread}[0]);
    $self->assert_num_equals(1, scalar @{$res->[0][1]{list}[0]{matchedIds}{Email}});
    $self->assert_str_equals($emailId, $res->[0][1]{list}[0]{matchedIds}{Email}[0]);
    $self->assert_num_equals(1, scalar @{$res->[0][1]{notFound}});
    $self->assert_str_equals('unknown', $res->[0][1]{notFound}[0]);
}
