#!perl
use Cassandane::Tiny;

sub test_calendarevent_defaultalerts_etag_preserved_after_alarm
    :min_version_3_9 :needs_component_jmap
{
    my ($self) = @_;

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

    xlog $self, "Set default alarms";
    my $res = $jmap->CallMethods([
        ['Calendar/set', {
            update => {
                Default => {
                    defaultAlertsWithTime => {
                        alert1 => {
                            '@type' => 'Alert',
                            trigger => {
                                '@type' => 'OffsetTrigger',
                                relativeTo => 'start',
                                offset => 'PT0S',
                            },
                            action => 'display',
                        }
                    },
                },
            },
        }, 'R1'],
    ]);
    $self->assert(exists $res->[0][1]{updated}{Default});

    xlog $self, "Create event that starts in a few seconds";
    my $eventUid = '5f0dec98-8952-418e-91fa-159cb2ba28da';
    my $now = DateTime->now();
    $now->set_time_zone('Etc/UTC');
    my $startdt = $now->clone();
    $startdt->add(DateTime::Duration->new(seconds => 2));

    $res = $jmap->CallMethods([
        ['CalendarEvent/set', {
            create => {
                event1 => {
                    uid => $eventUid,
                    calendarIds => {
                        'Default' => JSON::true,
                    },
                    title => "event1",
                    start => $startdt->strftime('%Y-%m-%dT%H:%M:%S'),
                    duration => "PT1H",
                    timeZone => "Etc/UTC",
                    useDefaultAlerts => JSON::true,
                },
            },
        }, 'R1'],
    ]);
    my $eventId = $res->[0][1]{created}{event1}{id};
    $self->assert_not_null($eventId);

    xlog $self, "Get event ETag before alarm fires";
    my %Headers;
    if ($caldav->{user}) {
        $Headers{'Authorization'} = $caldav->auth_header();
    }
    $res = $caldav->{ua}->request('HEAD',
        $caldav->request_url("Default/$eventUid.ics"),
        { headers => \%Headers, });

    my $etag = $res->{headers}{etag};
    $self->assert_not_null($etag);

    xlog $self, "Run calalarmd";
    $self->{instance}->getnotify();
    $self->{instance}->run_command({ cyrus => 1 },
        'calalarmd', '-t' => $now->epoch() + 60 );
    my $notifdata = $self->{instance}->getnotify();
    my @notifs;
    foreach (@$notifdata) {
        if ($_->{CLASS} eq 'EVENT') {
            my $e = decode_json($_->{MESSAGE});
            if ($e->{event} eq "CalendarAlarm") {
                push @notifs, $e;
            }
        }
    }
    $self->assert_num_equals(1, scalar @notifs);

    xlog $self, "Get event ETag after alarm fired";
    my %Headers;
    if ($caldav->{user}) {
        $Headers{'Authorization'} = $caldav->auth_header();
    }
    $res = $caldav->{ua}->request('HEAD',
        $caldav->request_url("Default/$eventUid.ics"),
        { headers => \%Headers, });

    xlog $self, "Assert ETag has not changed";
    my $oldEtag = $etag;
    my $newEtag = $res->{headers}{etag};
    $self->assert_str_equals($oldEtag, $newEtag);
}
