#!perl
use Cassandane::Tiny;

# An event added from public data (a PUBLISH with no ORGANIZER) can still
# be updated by the next such PUBLISH, though nothing else may schedule an
# event that has no stored ORGANIZER.
sub test_imip_publish_update_no_organizer
    :needs_component_httpd :want_service_http
    ($self)
{
    my $IMAP = $self->{store}->get_client();
    $self->{store}->_select();
    $IMAP->uid(1);
    $self->{store}->set_fetch_attributes(qw(uid flags));

    my $CalDAV = $self->{caldav};
    my $CalendarHref =
        $self->default_user->calendars->default->properties->{'x-href'};
    my $uuid = "6de280c9-edff-4019-8ebd-cfebc73f8201";

    xlog $self, "Install a sieve script to process public iMIP";
    $self->{instance}->install_sieve_script(<<EOF
require ["body", "variables", "imap4flags", "processcalendar"];
if body :content "text/calendar" :contains "\nMETHOD:" {
    processcalendar :allowpublic :outcome "outcome";
}
EOF
    );

    my $publish = sub ($seq, $summary) {
        my $imip = <<EOF;
Date: Thu, 23 Sep 2021 09:06:18 -0400
To: Cassandane <cassandane\@example.com>
Message-ID: <$uuid-$seq\@example.net>
Content-Type: text/calendar; method=PUBLISH; component=VEVENT
X-Cassandane-Unique: $uuid-$seq

BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example//NONSGML v1.0//EN
METHOD:PUBLISH
BEGIN:VEVENT
UID:$uuid
DTSTAMP:20210923T034327Z
DTSTART:20210923T193000Z
DURATION:PT3H
SEQUENCE:$seq
SUMMARY:$summary
END:VEVENT
END:VCALENDAR
EOF
        my $msg = Cassandane::Message->new(raw => $imip);
        $msg->set_attribute(uid => $seq + 1);
        $self->{instance}->deliver($msg);
    };

    xlog $self, "Deliver the first PUBLISH";
    $publish->(0, 'An Event');

    my $events = $CalDAV->GetEvents($CalendarHref);
    $self->assert_cmp_deeply(
        [ superhashof({ uid => $uuid, title => 'An Event' }) ],
        $events
    );

    xlog $self, "Deliver an updated PUBLISH";
    $publish->(1, 'An Updated Event');

    $events = $CalDAV->GetEvents($CalendarHref);
    $self->assert_cmp_deeply(
        [ superhashof({
            uid => $uuid,
            title => 'An Updated Event',
            sequence => 1,
        }) ],
        $events
    );
}
