#!perl
use Cassandane::Tiny;

sub test_card_set_create_relatedto
    :min_version_3_9 :needs_component_jmap :needs_dependency_icalvcard
{
    my ($self) = @_;
    my $jmap = $self->{jmap};

    my $service = $self->{instance}->get_service("http");
    $ENV{DEBUGDAV} = 1;
    my $carddav = Net::CardDAVTalk->new(
        user => 'cassandane',
        password => 'pass',
        host => $service->host(),
        port => $service->port(),
        scheme => 'http',
        url => '/',
        expandurl => 1,
    );

    my $id = 'ae2640cc-234a-4dd9-95cc-3106258445b9';
    my $href = "Default/$id.vcf";

    my $res = $jmap->CallMethods([
        ['ContactCard/set', {
            create => {
                "1" => {
                    '@type' => 'Card',
                    version => '1.0',
                    uid => $id,
                    name => { full => 'John Doe' },
                    relatedTo => {
                        'urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6' => {
                            '@type' => 'Relation',
                            relation => {
                                friend => JSON::true
                            }
                        },
                        'https://example.com/directory/john.vcf' => {
                            '@type' => 'Relation',
                            relation => {
                                contact => JSON::true
                            }
                        },
                        'Please contact my deputy John for any inquiries.' => {
                            '@type' => 'Relation',
                            relation => { }
                        }
                    }
                }
            }
        }, 'R1']
    ]);

    $self->assert_not_null($res->[0][1]{created}{1});

    $res = $carddav->Request('GET', $href, '',
                             'Accept' => 'text/vcard; version=4.0');

    my $card = $res->{content};
    $card =~ s/\r?\n[ \t]+//gs;  # unfold long properties

    $self->assert_matches(qr|RELATED;TYPE=FRIEND:urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6|, $card);
    $self->assert_matches(qr|RELATED;TYPE=CONTACT:https://example.com/directory/john.vcf|, $card);
    $self->assert_matches(qr|RELATED;VALUE=TEXT:Please contact my deputy John for any inquiries.|, $card);
    $self->assert_does_not_match(qr|JSPROP|, $card);
}
