#!perl
use Cassandane::Tiny;

sub test_email_query_fromanycontact_ignore_localpartonly
    :min_version_3_3 :needs_component_jmap :JMAPExtensions
    :needs_component_sieve
{
    my ($self) = @_;
    my $jmap = $self->{jmap};
    my $imap = $self->{store}->get_client();

    xlog "Create contact with localpart-only mail address";
    my $using = [
        'urn:ietf:params:jmap:core',
        'urn:ietf:params:jmap:mail',
        'https://cyrusimap.org/ns/jmap/mail',
        'https://cyrusimap.org/ns/jmap/contacts',
    ];

    my $res = $jmap->CallMethods([
        ['Contact/set', {
            create => {
                contact1 => {
                    emails => [{
                        type => 'personal',
                        value => 'email',
                    }],
                },
            }
        }, 'R1'],
    ], $using);
    my $contactId1 = $res->[0][1]{created}{contact1}{id};
    $self->assert_not_null($contactId1);

    xlog "Assert JMAP sieve ignores localpart-only contacts";
    $imap->create("INBOX.matches") or die;
    $self->{instance}->install_sieve_script(<<'EOF'
require ["x-cyrus-jmapquery", "x-cyrus-log", "variables", "fileinto"];
if
  allof( not string :is "${stop}" "Y",
    jmapquery text:
  {
    "operator" : "NOT",
    "conditions" : [
        {
           "fromAnyContact" : true
        }
    ]
  }
.
  )
{
  fileinto "INBOX.matches";
}
EOF
    );

    my $msg1 = $self->{gen}->generate(from => Cassandane::Address->new(
            localpart => 'email', domain => 'local'
    ));
    $self->{instance}->deliver($msg1);
    $self->{store}->set_fetch_attributes('uid');
    $self->{store}->set_folder('INBOX.matches');
    $self->check_messages({ 1 => $msg1 }, check_guid => 0);

    xlog "Assert Email/query ignores localpart-only contacts";
    $res = $jmap->CallMethods([
        ['Email/query', {
            filter => {
                operator => 'NOT',
                conditions => [{
                    fromAnyContact => JSON::true
                }]
            },
            sort => [
                { property => "subject" }
            ],
        }, 'R1']
    ], $using);
    $self->assert_num_equals(1, scalar @{$res->[0][1]{ids}});
}
