#!perl
use Cassandane::Tiny;

sub test_rewrite_webdav_attachment_binary_itip_caldav
    :min_version_3_5 :needs_component_jmap
{
    my ($self) = @_;
    my $caldav = $self->{caldav};

    xlog "Create event via CalDAV";
    my $rawIcal = <<'EOF';
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Apple Inc.//Mac OS X 10.10.4//EN
CALSCALE:GREGORIAN
BEGIN:VEVENT
CREATED:20150806T234327Z
ORGANIZER:cassandane@example.com
ATTENDEE:attendee@local
UID:123456789
TRANSP:OPAQUE
SUMMARY:test
DTSTART;TZID=Australia/Melbourne:20160831T153000
DURATION:PT1H
DTSTAMP:20150806T234327Z
SEQUENCE:0
END:VEVENT
END:VCALENDAR
EOF
    $caldav->Request('PUT', 'Default/test.ics', $rawIcal,
        'Content-Type' => 'text/calendar');
    my $eventHref = '/dav/calendars/user/cassandane/Default/test.ics';

    xlog "Add attachment via CalDAV";
    my $url = $caldav->request_url($eventHref) . '?action=attachment-add';
    my $res = $caldav->ua->post($url, {
        headers => {
            'Content-Type' => 'application/octet-stream',
            'Content-Disposition' => 'attachment;filename=test',
            'Prefer' => 'return=representation',
            'Authorization' => $caldav->auth_header(),
        },
        content => 'someblob',
    });
    $self->assert_str_equals('201', $res->{status});

    # Now we have a blob "someblob" (c29tZWJsb2I=) in managed attachments.

    xlog "Create event via CalDAV";
    $rawIcal = <<'EOF';
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Apple Inc.//Mac OS X 10.10.4//EN
CALSCALE:GREGORIAN
BEGIN:VEVENT
CREATED:20150806T234327Z
ORGANIZER:cassandane@example.com
ATTENDEE;PARTSTAT=DECLINED:attendee@local
UID:123456789
TRANSP:OPAQUE
SUMMARY:test
DTSTART;TZID=Australia/Melbourne:20160831T153000
DURATION:PT1H
DTSTAMP:20150806T234327Z
ATTACH;VALUE=BINARY:c29tZWJsb2I=
SEQUENCE:1
END:VEVENT
END:VCALENDAR
EOF
    $caldav->Request('PUT', 'Default/test.ics', $rawIcal,
        'Schedule-Sender-Address' => 'attendee@local',
        'Content-Type' => 'text/calendar');

    my $caldavResponse = $caldav->Request('GET', $eventHref);
    my $ical = Data::ICal->new(data => $caldavResponse->{content});
    my %entries = map { $_->ical_entry_type() => $_ } @{$ical->entries()};
    my $event = $entries{'VEVENT'};
    $self->assert_not_null($event);

    xlog "Assert BINARY ATTACH got rewritten to managed attachment URI";
    my $attach = $event->property('ATTACH');
    $self->assert_num_equals(1, scalar @{$attach});
    $self->assert_not_null($attach->[0]->parameters()->{'MANAGED-ID'});
    $self->assert_null($attach->[0]->parameters()->{VALUE});
    my $webdavAttachURI =
       $self->{instance}->{config}->get('webdav_attachments_baseurl') .
       '/dav/calendars/user/cassandane/Attachments/';
    $self->assert($attach->[0]->value() =~ /^$webdavAttachURI.+/);
}
