#!perl
use Cassandane::Tiny;

sub test_calendar_changes_shared
    :min_version_3_9 :JMAPExtensions
    ($self)
{
    my $jmap = $self->default_user->jmap;

    my $admin = $self->{adminstore}->get_client();

    my $assert_changes = sub ($sinceState, $changes)
    {
        my $res = $jmap->CallMethods([
            ['Calendar/changes', {
                    accountId => 'sharer',
                    sinceState => $sinceState,
                }, 'R1']
        ]);

        $self->assert_cmp_deeply($changes->{created}, $res->[0][1]{created});
        $self->assert_cmp_deeply($changes->{updated}, $res->[0][1]{updated});
        $self->assert_cmp_deeply($changes->{destroyed}, $res->[0][1]{destroyed});
        $self->assert_str_equals($sinceState, $res->[0][1]{oldState});

        return $res->[0][1]{newState};
    };

    my $assert_calendars = sub ($calendars)
    {
        my $res = $jmap->CallMethods([
            ['Calendar/get', {
                accountId => 'sharer',
                properties => ['id'],
            }, 'R1']
        ]);

        my @wantCalendars = sort @{$calendars};
        my @haveCalendars = sort map { $_->{id} } @{$res->[0][1]{list}};
        $self->assert_cmp_deeply(\@wantCalendars, \@haveCalendars);
    };

    xlog $self, "Create sharer and share default calendar";
    my $sharer_user = $self->create_user_and_allocate_calendar('sharer');
    my $sharerJmap = $sharer_user->jmap;
    my $sharerDefaultCalendar = $sharer_user->calendars->default;

    my ($dav_id) =
      $sharerDefaultCalendar->properties->{'x-href'} =~ m{/([^/]+)\z};

    $sharerDefaultCalendar->share_with(cassandane => 'mayReadItems');

    xlog $self, "Sharee gets initial calendar state";
    my $res = $jmap->CallMethods([
        ['Calendar/get', {
            accountId => 'sharer',
        }, 'R1']
    ]);
    my $state = $res->[0][1]{state};
    $self->assert_not_null($state);
    $assert_calendars->([ $sharerDefaultCalendar->id ]);

    xlog $self, "Sharer creates unshared calendars A and B";

    my $calendarA = $sharer_user->calendars->create({ name => 'A' });
    my $calendarB = $sharer_user->calendars->create({ name => 'B' });

    $state = $assert_changes->($state, {
        created => [],
        updated => [],
        destroyed => []
    });
    $assert_calendars->([ $sharerDefaultCalendar->id ]);

    xlog $self, "Sharer creates and shares calendar C";
    $res = $sharerJmap->CallMethods([
        ['Calendar/set', {
            create => {
                calC => {
                    name => 'C',
                    shareWith => {
                        cassandane => {
                            mayReadFreeBusy => JSON::true,
                            mayReadItems => JSON::true,
                            mayUpdatePrivate => JSON::true,
                            mayRSVP => JSON::true,
                        },
                    },
                },
            },
        }, 'R1'],
    ]);
    my $calendarC_id = $res->[0][1]{created}{calC}{id};
    $self->assert_not_null($calendarC_id);

    $state = $assert_changes->($state, {
        created => [$calendarC_id],
        updated => [],
        destroyed => []
    });
    $assert_calendars->([ $sharerDefaultCalendar->id, $calendarC_id ]);

    xlog $self, "Sharer shares calendar A";
    $res = $sharerJmap->CallMethods([
        ['Calendar/set', {
            update => {
                $calendarA->id => {
                    shareWith => {
                        cassandane => {
                            mayReadFreeBusy => JSON::true,
                            mayReadItems => JSON::true,
                        },
                    },
                },
            },
        }, 'R1'],
    ]);
    $self->assert(exists $res->[0][1]{updated}{$calendarA->id});

    $state = $assert_changes->($state, {
        created => [],
        updated => [$calendarA->id], # XXX this might better be in 'created'
        destroyed => []
    });
    $assert_calendars->([ $sharerDefaultCalendar->id, $calendarA->id, $calendarC_id]);

    xlog $self, "Sharer shares calendar B with anyone";

    # We can't use JMAP here because you (apparently?) can't use it for
    # "anyone". -- rjbs, 2026-07-19
    my ($dav_id_B) = $calendarB->properties->{'x-href'} =~ m{/([^/]+)\z};
    $admin->setacl("user.sharer.#calendars.$dav_id_B", anyone => 'lrs');

    $state = $assert_changes->($state, {
        created => [],
        updated => [$calendarB->id], # XXX this might better be in 'created'
        destroyed => []
    });
    $assert_calendars->([ $sharerDefaultCalendar->id, $calendarA->id, $calendarB->id, $calendarC_id]);

    xlog $self, "Sharee gets write rights on calendar C";
    $res = $sharerJmap->CallMethods([
        ['Calendar/set', {
            update => {
                $calendarC_id => {
                    'shareWith/cassandane/mayWriteAll' => JSON::true,
                },
            },
        }, 'R1'],
    ]);

    $state = $assert_changes->($state, {
        created => [],
        updated => [$calendarC_id],
        destroyed => []
    });
    $assert_calendars->([ $sharerDefaultCalendar->id, $calendarA->id, $calendarB->id, $calendarC_id ]);

    xlog $self, "Sharee looses write rights on calendar C";
    $res = $sharerJmap->CallMethods([
        ['Calendar/set', {
            update => {
                $calendarC_id => {
                    'shareWith/cassandane/mayWriteAll' => JSON::false,
                },
            },
        }, 'R1'],
    ]);

    $state = $assert_changes->($state, {
        created => [],
        updated => [$calendarC_id],
        destroyed => []
    });
    $assert_calendars->([ $sharerDefaultCalendar->id, $calendarA->id, $calendarB->id, $calendarC_id ]);

    xlog $self, "Sharer unshares calendar C";
    $res = $sharerJmap->CallMethods([
        ['Calendar/set', {
            update => {
                $calendarC_id => {
                    'shareWith/cassandane' => undef,
                },
            },
        }, 'R1'],
    ]);
    $assert_calendars->([ $sharerDefaultCalendar->id, $calendarA->id, $calendarB->id ]);

    $state = $assert_changes->($state, {
        created => [],
        updated => [],
        destroyed => [$calendarC_id]
    });

    xlog $self, "Sharer unshares calendar B for anyone";

    # We can't use JMAP here because you (apparently?) can't use it for
    # "anyone". -- rjbs, 2026-07-19
    $admin->setacl("user.sharer.#calendars.$dav_id_B", anyone => '');

    $state = $assert_changes->($state, {
        created => [],
        updated => [],
        destroyed => [$calendarB->id]
    });
    $assert_calendars->([ $sharerDefaultCalendar->id, $calendarA->id ]);

    xlog $self, "Sharer destroys calendar A";
    $res = $sharerJmap->CallMethods([
        ['Calendar/set', {
            destroy => [$calendarA->id],
        }, 'R1'],
    ]);
    $self->assert_cmp_deeply([$calendarA->id], $res->[0][1]{destroyed});

    $state = $assert_changes->($state, {
        created => [],
        updated => [],
        destroyed => [$calendarA->id]
    });
    $assert_calendars->([ $sharerDefaultCalendar->id ]);
}

