#!perl
use Cassandane::Tiny;

# Another test for issues with createdmodseq tracking, making sure that if we
# could know an object existed at a state, then /changes from that state much
# show it as being destroyed (if it was).

sub test_calendarevent_changes_destroy_after_dav_reconstruct ($self)
{
    my $jmap = $self->default_user->jmap;
    my $calid = $self->default_user->calendars->default->id;

    xlog $self, "create an event";
    my $res = $jmap->CallMethods([['CalendarEvent/set', { create => {
        1 => {
            version => '2.0',
            calendarIds => { $calid => JSON::true },
            title => 'original',
            start => '2026-02-01T12:00:00',
            timeZone => 'Europe/Berlin',
            duration => 'PT1H',
        },
    }}, 'R1']]);
    my $id = $res->[0][1]{created}{1}{id};
    $self->assert_not_null($id);

    # State after creation: the event's createdmodseq is <= this, so a client
    # syncing from here has seen the event and must be told if it is destroyed.
    my $state_after_create = $res->[0][1]{newState};

    xlog $self, "edit the event so its modseq advances past its createdmodseq";
    $res = $jmap->CallMethods([['CalendarEvent/set', { update => {
        $id => { title => 'edited' },
    }}, 'R1']]);
    $self->assert(exists $res->[0][1]{updated}{$id});

    xlog $self, "rebuild dav.db from scratch (reproduces the migration backfill)";
    $self->{instance}->run_command({ cyrus => 1 }, 'dav_reconstruct', 'cassandane');

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

    xlog $self, "a client that had seen the event must be told it was destroyed";
    $res = $jmap->CallMethods([['CalendarEvent/changes', {
        sinceState => $state_after_create,
    }, 'R1']]);
    $self->assert_deep_equals([$id], $res->[0][1]{destroyed});
    $self->assert_deep_equals([], $res->[0][1]{created});
    $self->assert_deep_equals([], $res->[0][1]{updated});
}
