#!perl
use Cassandane::Tiny;
use Encode qw(decode);

sub test_card_set_preserve_xprops
    ($self)
{
    my $jmap    = $self->{jmap};
    my $carddav = $self->{carddav};

    xlog $self, "Create vCard with x-property";
    my $card = decode(
        'utf-8', <<EOF
BEGIN:VCARD
VERSION:3.0
UID:0A8F88DE-1073-4D47-926F-0D535523FD15
N:Smith;Hank;;
FN:Hank Smith
X-FOO;X-BAZ=Bam:Bar
REV:2008-04-24T19:52:43Z
END:VCARD
EOF
    );
    $card =~ s/\r?\n/\r\n/gs;
    $carddav->Request('PUT', 'Default/test.vcf', $card, 'Content-Type' => 'text/vcard');

    xlog $self, "Update some contact property";
    my $res = $jmap->CallMethods([
        [ 'ContactCard/query', {}, 'R1' ],
        [
            'ContactCard/get',
            {
                '#ids' => {
                    resultOf => 'R1',
                    path     => '/ids',
                    name     => 'ContactCard/query',
                },
                properties => ['name'],
            },
            'R2'
        ],
    ]);

    my $contactId = $res->[0][1]{ids}[0];
    $self->assert_not_null($contactId);
    $self->assert_str_equals('Hank Smith', $res->[1][1]{list}[0]{name}{full});

    $res = $jmap->CallMethods([
        [
            'ContactCard/set',
            {
                update => {
                    $contactId => {
                        'name/full' => 'Hank Kraut',
                    }
                },
            },
            'R1'
        ],
        [
            'ContactCard/get',
            {
                ids        => [$contactId],
                properties => ['name'],
            },
            'R2'
        ],
    ]);
    $self->assert_str_equals('Hank Kraut', $res->[1][1]{list}[0]{name}{full});

    xlog $self, "Update x-property is preserved in vCard";
    $res = $carddav->Request('GET', 'Default/test.vcf');
    $self->assert_matches(qr/^X-FOO;X-BAZ=Bam:Bar\r?$/m, $res->{content});
}
