#!perl
use Cassandane::Tiny;

sub assert_fetch_threadid ($self, $have_threads)
{
    my $talk = $self->{store}->get_client();

    xlog $self, "generating three messages, two of them a thread";
    my $msg_a = $self->make_message("Message A");
    $self->make_message("Message B");
    $self->make_message("Re: Message A", references => [ $msg_a ]);

    $talk->select('INBOX');
    my $res = $talk->fetch('1:*', '(emailid threadid)');

    my $objectid = re(qr/\A[A-Za-z0-9_-]{1,255}\z/);

    # Without conversations RFC 8474 wants THREADID NIL, which IMAPTalk
    # gives us as undef.  "(NIL)" would be [ undef ]: the objectid "NIL".
    my $threadid = $have_threads ? [ $objectid ] : undef;

    $self->assert_cmp_deeply(
        {
            map {
                $_ => {
                    uid => $_,
                    emailid => [ $objectid ],
                    threadid => $threadid,
                }
            } 1..3
        },
        $res,
    );

    return if !$have_threads;

    $self->assert_str_equals($res->{1}{threadid}[0], $res->{3}{threadid}[0]);
    $self->assert_str_not_equals($res->{1}{threadid}[0],
                                 $res->{2}{threadid}[0]);
}

sub test_fetch_threadid__conversations
    ($self)
{
    $self->assert_fetch_threadid(1);
}

sub test_fetch_threadid__noconversations
    :NoConversations
    ($self)
{
    $self->assert_fetch_threadid(0);
}
