#!perl
use Cassandane::Tiny;

sub test_emailsubmission_send_delay_auditlog
    :min_version_3_13 :needs_component_calalarmd
    ($self)
{
    return if !$self->{instance}->{have_syslog_replacement};

    my $jmap = $self->{jmap};

    my $res = $jmap->CallMethods([['Identity/get', {}, "R0"]]);
    my $identityid = $res->[0][1]->{list}[0]->{id};
    $self->assert_not_null($identityid);

    xlog $self, "Generate an email via IMAP";
    $self->make_message("foo", body => "a body\r\n") or die;

    $res = $jmap->CallMethods([['Email/query', {}, "R1"]]);
    my $emailid = $res->[0][1]->{ids}[0];

    xlog $self, "create a scheduled (held) email submission";
    $res = $jmap->CallMethods([['EmailSubmission/set', {
        create => {
            '1' => {
                identityId => $identityid,
                emailId  => $emailid,
                envelope => {
                    mailFrom => {
                        email => 'from@localhost',
                        parameters => { "holdfor" => "30" },
                    },
                    rcptTo => [
                        { email => 'rcpt1@localhost' },
                        { email => 'rcpt2@localhost' },
                    ],
                },
            },
        },
    }, "R2"]]);
    my $subid = $res->[0][1]->{created}{1}{id};
    $self->assert_not_null($subid);

    # drain syslog so we only see lines from the calalarmd run below
    $self->{instance}->getsyslog();

    xlog $self, "trigger delivery well after the scheduled time";
    my $now = DateTime->now();
    $self->{instance}->run_command({ cyrus => 1 }, 'calalarmd',
                                   '-t' => $now->epoch() + 120);

    $res = $jmap->CallMethods([['EmailSubmission/get',
                                { ids => [$subid] }, "R3"]]);
    $self->assert_str_equals('final',
                             $res->[0][1]->{list}[0]->{undoStatus});

    xlog $self, "audit log records the send with a parseable delay";
    my @lines = $self->{instance}->getsyslog(
        qr/auditlog\.calalarmd\.send\.futurerelease/);
    $self->assert_num_equals(1, scalar @lines);
    $self->assert_matches(qr/send\.outcome=<?sent>?/, $lines[0]);
    $self->assert_matches(qr/send\.delay=<?\d+>?/, $lines[0]);
    $self->assert_matches(qr/send\.numrcpts=<?2>?/, $lines[0]);
}
