#!perl
use Cassandane::Tiny;

# A memo carries the blobId of the message it annotates in X-ME-Memo-For.
# The message-id index only records a conversation's base cid, so this
# header is the only way a memo can find the right side of a split.
sub test_email_set_create_memo_for_splitconv
  : ConversationsMaxThread10
    ($self)
{
  my $jmap = $self->{jmap};

  xlog $self, "Create conversation with maximum thread count";
  my $convsMaxThread
    = $self->{instance}->{config}->get('conversations_max_thread');
  $self->make_message('Email A', messageid => "msg1\@example.com");
  my $lastUid = 1;
  foreach my $i (2 .. $convsMaxThread) {
    my $nextUid = $lastUid + 1;
    $self->make_message(
      "Re: Email A",
      messageid     => "msg$nextUid\@example.com",
      extra_headers => [ [ "in-reply-to", "<msg$lastUid\@example.com>" ], ],
    );
    $lastUid = $nextUid;
  }

  xlog $self, "Append one more reply, splitting the conversation";
  my $splitUid = $lastUid + 1;
  $self->make_message(
    "Re: Email A",
    messageid     => "msg$splitUid\@example.com",
    extra_headers => [ [ "in-reply-to", "<msg$lastUid\@example.com>" ], ],
  );

  my $res = $jmap->CallMethods([
    [ 'Email/query', {}, 'R1' ],
    [
      'Email/get',
      {
        '#ids' => {
          resultOf => 'R1',
          name     => 'Email/query',
          path     => '/ids'
        },
        properties => [ 'threadId', 'messageId', 'blobId' ],
      },
      'R2'
    ],
  ]);

  my %byMsgId = map { $_->{messageId}[0] => $_ } @{ $res->[1][1]{list} };

  my $base  = $byMsgId{"msg1\@example.com"};
  my $split = $byMsgId{"msg$splitUid\@example.com"};
  $self->assert_not_null($base->{threadId});
  $self->assert_not_null($split->{threadId});
  $self->assert_str_not_equals($base->{threadId}, $split->{threadId});

  my $make_memo = sub ($name, $parent) {
    return {
      mailboxIds           => { '$inbox' => JSON::true },
      from                 => [ { email => 'from@local' } ],
      subject              => "Re: Email A",
      messageId            => ["$name\@example.com"],
      inReplyTo            => $parent->{messageId},
      'header:X-ME-Memo-For' => $parent->{blobId},
      bodyStructure        => {
        type   => 'text/plain',
        partId => 'part1',
      },
      bodyValues => { part1 => { value => "memo $name" } },
      keywords   => { '$memo' => JSON::true },
    };
  };

  xlog $self, "Create memos on a message in each half of the split";
  $res = $jmap->CallMethods([
    [
      'Email/set',
      {
        create => {
          memoBase  => $make_memo->('memoBase',  $base),
          memoSplit => $make_memo->('memoSplit', $split),
        },
      },
      'R1'
    ],
  ]);

  xlog $self, "Each memo joins the thread of the message it annotates";
  $self->assert_str_equals(
    $base->{threadId},
    $res->[0][1]{created}{memoBase}{threadId}
  );
  $self->assert_str_equals(
    $split->{threadId},
    $res->[0][1]{created}{memoSplit}{threadId}
  );
}
