#!perl
use Cassandane::Tiny;

sub test_contactgroup_set_update_v4
    :min_version_3_9
{

    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 $contact1 = '60f60d95-1f33-480c-bfd6-02b93a07aefc';
    my $contact2 = '3e7cfbaf-3199-41bd-8749-38b8d1c89605';
    my $contact3 = '5b3b9ce1-0b5e-4cbd-8add-018321cad51b';
    my $href = "Default/$id.vcf";
    my $card = <<EOF;
BEGIN:VCARD
VERSION:4.0
UID:$id
KIND:group
MEMBER:urn:uuid:$contact1
MEMBER:urn:uuid:$contact2
MEMBER:urn:uuid:$contact3
FN:Test
REV:20220217T152253Z
N:Test
END:VCARD
EOF

    $card =~ s/\r?\n/\r\n/gs;
    $carddav->Request('PUT', $href, $card, 'Content-Type' => 'text/vcard');

    my $res = $jmap->CallMethods([
        ['ContactGroup/get', {
        }, 'R1']
    ]);
    $self->assert_str_equals($id, $res->[0][1]{list}[0]{id});
    $self->assert_str_equals('Test', $res->[0][1]{list}[0]{name});
    $self->assert_num_equals(3, scalar @{$res->[0][1]{list}[0]{contactIds}});
    $self->assert_str_equals($contact1, $res->[0][1]{list}[0]{contactIds}[0]);
    $self->assert_str_equals($contact2, $res->[0][1]{list}[0]{contactIds}[1]);
    $self->assert_str_equals($contact3, $res->[0][1]{list}[0]{contactIds}[2]);

    xlog $self, "update contact group by removing a member and reordering";
    $res = $jmap->CallMethods([['ContactGroup/set', {update => {
                        $id => {name => "group1", contactIds => [$contact3, $contact1]}
                    }}, "R4"]]);

    $self->assert_str_equals('ContactGroup/set', $res->[0][0]);
    $self->assert(exists $res->[0][1]{updated}{$id});

    xlog $self, "get contact group $id";
    $res = $jmap->CallMethods([['ContactGroup/get', { ids => [$id] }, "R3"]]);
    $self->assert(exists $res->[0][1]{list}[0]{contactIds});
    $self->assert_num_equals(2, scalar @{$res->[0][1]{list}[0]{contactIds}});
    $self->assert_str_equals($contact3, $res->[0][1]{list}[0]{contactIds}[0]);
    $self->assert_str_equals($contact1, $res->[0][1]{list}[0]{contactIds}[1]);
}
