#!perl
use Cassandane::Tiny;

# After a dav_reconstruct, a destroyed standalone instance must still be
# reported as destroyed to a client that had synced it before it was destroyed.
sub test_calendarevent_changes_standalone_destroy_after_dav_reconstruct ($self)
{
    my $jmap = $self->default_user->jmap;
    my $calid = $self->default_user->calendars->default->id;

    xlog $self, "create the first standalone instance";
    my $res = $jmap->CallMethods([['CalendarEvent/set', { create => {
        i1 => {
            version => '2.0',
            calendarIds => { $calid => JSON::true },
            uid => 'event1uid',
            title => 'instance1',
            start => '2026-01-01T11:11:11',
            timeZone => 'Europe/Berlin',
            duration => 'PT1H',
            recurrenceId => '2026-01-01T11:11:11',
            recurrenceIdTimeZone => 'Europe/Berlin',
        },
    }}, 'R1']]);
    my $id1 = $res->[0][1]{created}{i1}{id};
    $self->assert_not_null($id1);

    # The client syncs here: it has instance1 but not yet instance2.
    my $state1 = $res->[0][1]{newState};

    xlog $self, "create a second standalone instance with the same uid";
    $res = $jmap->CallMethods([['CalendarEvent/set', { create => {
        i2 => {
            version => '2.0',
            calendarIds => { $calid => JSON::true },
            uid => 'event1uid',
            title => 'instance2',
            start => '2026-02-02T22:22:22',
            timeZone => 'Europe/Berlin',
            duration => 'PT1H',
            recurrenceId => '2026-02-02T22:22:22',
            recurrenceIdTimeZone => 'Europe/Berlin',
        },
    }}, 'R1']]);
    $self->assert_not_null($res->[0][1]{created}{i2}{id});

    xlog $self, "rebuild dav.db from scratch (clobbers instance1's createdmodseq)";
    $self->{instance}->run_command({ cyrus => 1 }, 'dav_reconstruct', 'cassandane');

    xlog $self, "destroy the first instance";
    $res = $jmap->CallMethods([['CalendarEvent/set', {
        destroy => [ $id1 ],
    }, 'R1']]);
    $self->assert_deep_equals([$id1], $res->[0][1]{destroyed});

    xlog $self, "a client that had instance1 must be told it was destroyed";
    $res = $jmap->CallMethods([['CalendarEvent/changes', {
        sinceState => $state1,
    }, 'R1']]);
    $self->assert_deep_equals([$id1], $res->[0][1]{destroyed});
}
