#!perl
use Cassandane::Tiny;

sub test_contact_set_uid
    :min_version_3_1
{
    my ($self) = @_;

    my $jmap = $self->{jmap};

    # An empty UID generates a random uid.
    my $res = $jmap->CallMethods([
        ['Contact/set', {
            create => {
                "1" => {
                    firstName => "first1",
                    lastName => "last1",
                }
            }
        }, "R1"],
        ['Contact/get', { ids => ['#1'] }, 'R2'],
    ]);
    $self->assert_not_null($res->[1][1]{list}[0]{uid});
    $jmap->{CreatedIds} = {};

    # A sane UID maps to both the JMAP id and the DAV resource.
    $res = $jmap->CallMethods([
        ['Contact/set', {
            create => {
                "2" => {
                    firstName => "first2",
                    lastName => "last2",
                    uid => '1234-56789-01234-56789',
                }
            }
        }, "R1"],
        ['Contact/get', { ids => ['#2'] }, 'R2'],
    ]);
    $self->assert_not_null($res->[1][1]{list}[0]{uid});
    my($filename, $dirs, $suffix) = fileparse($res->[1][1]{list}[0]{"x-href"}, ".vcf");
    $self->assert_not_null($res->[1][1]{list}[0]->{id});
    $self->assert_str_equals($res->[1][1]{list}[0]->{uid}, $res->[1][1]{list}[0]->{id});
    $self->assert_str_equals($filename, $res->[1][1]{list}[0]->{id});
    $jmap->{CreatedIds} = {};

    # A non-pathsafe UID maps to uid but not the DAV resource.
    $res = $jmap->CallMethods([
        ['Contact/set', {
            create => {
                "3" => {
                    firstName => "first3",
                    lastName => "last3",
                    uid => 'a/bogus/path#uid',
                }
            }
        }, "R1"],
        ['Contact/get', { ids => ['#3'] }, 'R2'],
    ]);
    $self->assert_not_null($res->[1][1]{list}[0]{uid});
    ($filename, $dirs, $suffix) = fileparse($res->[1][1]{list}[0]{"x-href"}, ".vcf");
    $self->assert_not_null($res->[1][1]{list}[0]->{id});
    $self->assert_str_equals($res->[1][1]{list}[0]->{id}, $res->[1][1]{list}[0]->{uid});
    $self->assert_str_not_equals('path#uid', $filename);
    $jmap->{CreatedIds} = {};

    # Can't change an UID
    my $contactId = $res->[0][1]{created}{3}{id};
    $self->assert_not_null($contactId);
    $res = $jmap->CallMethods([
        ['Contact/set', {
            update => {
                $contactId => {
                    uid => '0000-1234-56789-01234-56789-000'
                }
            }
        }, "R1"],
    ]);
    $self->assert_str_equals('uid', $res->[0][1]{notUpdated}{$contactId}{properties}[0]);
    $jmap->{CreatedIds} = {};

}
