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

sub test_contact_set_preserve_xprops
  : needs_component_jmap {
    my ($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([
        [ 'Contact/query', {}, 'R1' ],
        [
            'Contact/get',
            {
                '#ids' => {
                    resultOf => 'R1',
                    path     => '/ids',
                    name     => 'Contact/query',
                },
                properties => ['lastName'],
            },
            'R2'
        ],
    ]);

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

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

    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});
}
