#!perl
use Cassandane::Tiny;

sub test_sieve_test_include_global_domain
    :JMAPExtensions :VirtDomains
    ($self)
{
    my $user = $self->{instance}->create_user('foo@example.com');
    my $jmap = $user->new_jmaptester;
    $jmap->DefaultUsing($self->jmap_default_using);

    my sub install ($username, $name, $mailbox) {
        $self->{instance}->install_sieve_script(
            "require \"fileinto\";\r\nfileinto \"$mailbox\";\r\n",
            username => $username, name => $name);
    }

    xlog "install domain and server-wide global scripts";
    install('@example.com', 'dscript', 'DOMAIN');
    install('', 'dscript', 'SERVER');
    install('', 'gscript', 'GLOBAL');

    my $email = to_crlf(<<'EOF');
From: "Some Example Sender" <example@example.com>
To: foo@example.com
Subject: test email
Date: Wed, 7 Dec 2016 22:11:11 +1100
MIME-Version: 1.0
Content-Type: text/plain; charset="UTF-8"

This is a test email.
EOF
    my $emailid = $jmap->Upload($email, "message/rfc822")->{blobId};

    my sub test_include ($name) {
        my $script = to_crlf(<<EOF);
require ["include"];
include :global "$name";
EOF
        my $scriptid = $jmap->Upload($script, "application/sieve")->{blobId};

        my $res = $jmap->CallMethods([
            ['SieveScript/test', {
                scriptBlobId => $scriptid,
                emailBlobIds => [ $emailid ],
            }, "R1"]
        ]);
        return $res->[0][1];
    }

    my sub included ($mailbox) {
        return {
            accountId => 'foo@example.com',
            completed => { $emailid => [ [ 'fileinto', { }, [ $mailbox ] ] ] },
            notCompleted => undef,
        };
    }

    xlog "a domain global script takes precedence over a server-wide one";
    $self->assert_cmp_deeply(included('DOMAIN'), test_include('dscript'));

    xlog "without a domain global script, the server-wide one is used";
    $self->assert_cmp_deeply(included('GLOBAL'), test_include('gscript'));
}
