#!perl
use Cassandane::Tiny;

# Blob/lookup must map a calendar resource's blob to CalendarEvent ids that
# CalendarEvent/get can actually resolve.  This is a regression test for a bug
# where CalendarEvent ids were produced from jscal_objs.added_at_modseq instead
# of ical_objs.createdmodseq.
sub test_calendarevent_blob_lookup_standalone_instances ($self)
{
    my $jmap = $self->default_user->jmap;
    my $calid = $self->default_user->calendars->default->id;

    xlog $self, "create the first standalone instance";
    my $res = $jmap->CallMethods([['CalendarEvent/set', { create => {
        i1 => {
            version => '2.0',
            calendarIds => { $calid => JSON::true },
            uid => 'event1uid',
            title => 'instance1',
            start => '2026-01-01T11:11:11',
            timeZone => 'Europe/Berlin',
            duration => 'PT1H',
            recurrenceId => '2026-01-01T11:11:11',
            recurrenceIdTimeZone => 'Europe/Berlin',
        },
    }}, 'R1']]);
    my $id1 = $res->[0][1]{created}{i1}{id};
    $self->assert_not_null($id1);

    xlog $self, "create a second standalone instance with the same uid";
    $res = $jmap->CallMethods([['CalendarEvent/set', { create => {
        i2 => {
            version => '2.0',
            calendarIds => { $calid => JSON::true },
            uid => 'event1uid',
            title => 'instance2',
            start => '2026-02-02T22:22:22',
            timeZone => 'Europe/Berlin',
            duration => 'PT1H',
            recurrenceId => '2026-02-02T22:22:22',
            recurrenceIdTimeZone => 'Europe/Berlin',
        },
    }}, 'R1']]);
    my $id2 = $res->[0][1]{created}{i2}{id};
    $self->assert_not_null($id2);

    # Both instances now live in one resource, so they share one blob.
    my $blobId = $res->[0][1]{created}{i2}{blobId};
    $self->assert_not_null($blobId);

    xlog $self, "Blob/lookup must return both ids, and they must resolve";
    $res = $jmap->CallMethods([['Blob/lookup', {
        typeNames => ['CalendarEvent'],
        ids => [$blobId],
    }, 'R1']], [
        'urn:ietf:params:jmap:core',
        'urn:ietf:params:jmap:blob',
    ]);
    $self->assert_deep_equals([sort($id1, $id2)],
        [sort @{$res->[0][1]{list}[0]{matchedIds}{CalendarEvent}}]);
}
