#!perl
use Cassandane::Tiny;

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

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

    # An empty UID generates a random uid.
    my $res = $jmap->CallMethods([
        ['ContactGroup/set', {
            create => {
                "1" => {
                    name => "name1",
                }
            }
        }, "R1"],
        ['ContactGroup/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([
        ['ContactGroup/set', {
            create => {
                "2" => {
                    name => "name2",
                    uid => '1234-56789-01234-56789',
                }
            }
        }, "R1"],
        ['ContactGroup/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([
        ['ContactGroup/set', {
            create => {
                "3" => {
                    name => "name3",
                    uid => 'a/bogus/path#uid',
                }
            }
        }, "R1"],
        ['ContactGroup/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([
        ['ContactGroup/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} = {};

}
