#!perl
use Cassandane::Tiny;
use experimental 'signatures';

# The Schedule-Address request header names the address a request schedules
# as.  Naming an address that belongs to another local user must not change
# the copy that user's attendee holds.
sub test_schedule_organizer_address_header
    :NoAltNameSpace
    ($self)
{
    my $admintalk = $self->{adminstore}->get_client();
    $admintalk->create("user.test");
    $admintalk->create("user.other");

    my $service = $self->{instance}->get_service("http");
    my sub caldav_for ($user) {
        return Net::CalDAVTalk->new(
            user => $user,
            password => 'pass',
            host => $service->host(),
            port => $service->port(),
            scheme => 'http',
            url => '/',
            expandurl => 1,
        );
    }
    my $testtalk = caldav_for('test');
    my $othertalk = caldav_for('other');
    $testtalk->GetCalendars();
    $othertalk->GetCalendars();

    my $uuid = $self->{caldav}->genuuid();
    my sub event ($sequence, $summary) {
        return <<~EOF;
            BEGIN:VCALENDAR
            VERSION:2.0
            PRODID:-//Cassandane//EN
            BEGIN:VEVENT
            UID:$uuid
            DTSTAMP:20260901T120000Z
            DTSTART:20260915T090000Z
            DTEND:20260915T100000Z
            SEQUENCE:$sequence
            SUMMARY:$summary
            ORGANIZER:MAILTO:cassandane\@example.com
            ATTENDEE;PARTSTAT=ACCEPTED:MAILTO:cassandane\@example.com
            ATTENDEE;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:test\@example.com
            END:VEVENT
            END:VCALENDAR
            EOF
    }
    my sub attendee_summary () {
        my ($event) = grep { $_->{uid} eq $uuid }
                           @{$testtalk->GetEvents('Default')};
        $self->assert_not_null($event);
        return $event->{title};
    }

    xlog $self, "organizer invites a local attendee";
    my $CalendarId = $self->{caldav}->NewCalendar({name => 'organizer'});
    $self->{caldav}->Request('PUT', "$CalendarId/$uuid.ics",
                             event(0, 'Budget review'),
                             'Content-Type' => 'text/calendar');
    $self->assert_str_equals('Budget review', attendee_summary());

    xlog $self, "another user stores a later SEQUENCE, naming the organizer's address in Schedule-Address";
    my $OtherCalendarId = $othertalk->NewCalendar({name => 'other'});
    $othertalk->Request('PUT', "$OtherCalendarId/$uuid.ics",
                        event(1, 'Cancelled, see new invite'),
                        'Content-Type' => 'text/calendar',
                        'Schedule-Address' => 'cassandane@example.com');

    $self->assert_str_equals('Budget review', attendee_summary());
}
