use Test::More;
use t::TestPsgi;
use LWP::Protocol::PSGI;
use JSON;
use Plack::Test;
use HTTP::Request::Common;

my $postedValues;

LWP::Protocol::PSGI->register(
    sub {
        my $req = Plack::Request->new(@_);
        ok( $req->method =~ /^post$/i, 'Method is POST' );
        ok( ( $req->uri eq 'http://localhost:3100/loki/api/v1/push' ),
            'URL is good' );
        my $s = $req->content;
        ok( $s = eval { JSON::from_json($s) }, 'Posted values are JSON' );
        push @$postedValues, $s;
        return [ 200, [], [] ];
    }
);
subtest "Check Loki API" => sub {
    my $args = {
        logger      => 't::TestLogger',
        userLogger  => 'Lemonldap::NG::Common::Logger::Loki',
        auditLogger => 'Lemonldap::NG::Common::AuditLogger::UserLoggerJSON',
        logLevel    => 'info',
    };
    my $psgi = new_ok( 't::TestPsgi' => [$args] );
    $psgi->init($args);

    my $server = Plack::Test->create( $psgi->run );
    my $res    = $server->request( GET "/" );
    is( $res->code, 200, "Returned HTTP code 200" );
    my $i;
    foreach my $a (@$postedValues) {
        is( $a->{streams}->[0]->{stream}->{job}, 'llng', 'job is llng' );
        ok( $a->{streams}->[0]->{stream}->{level} =~ /^(info|notice)$/,
            "log level is $1" );
        ok( $a->{streams}->[0]->{stream}->{instance}, 'instance exists' );
        is( $a->{streams}->[0]->{stream}->{env}, 'prod', 'env is prod' );
        ok( $a->{streams}->[0]->{values}->[0]->[0] =~ /^\d+$/,
            'timestamp is set' );
        my $msg = $a->{streams}->[0]->{values}->[0]->[1];
        ok( $msg, 'Message exists' );

   # First message is generated by userLogger, so a string, nexts are audit logs
        if ($i) {
            my $j = eval { JSON::from_json($msg) };
            ok( ( $j and ref $j ), 'Audit messgae is JSON encoded' );
        }
        else {
            ok(
                ( $msg eq 'User logger trace' ),
                'Userlogger message is a string'
            );
        }
        $i++;
    }
};

done_testing();
