### ----------------------------------------------------
### -- Cro::RPC::JSON
### -- Licenses: Artistic-2.0
### -- Authors: Vadim Belman <vrurg@lflat.org>
### -- File: t/011-message.rakutest
### ----------------------------------------------------
use Test;
use Cro::RPC::JSON:api<2>;
use Cro::RPC::JSON::Message:api<2>;
use Cro::RPC::JSON::MethodResponse:api<2>;
use Cro::RPC::JSON::Request:api<2>;
use Cro::HTTP::Request;

plan 3;

my @errParams =
    %(
        :code(-32600),
        :message("неважлио зовсім"),
        :data( { info => "а тут трохи докладніше про те, що не має ніякого значення" } ),
    ),
    %(
        :code(-32600),
        :message("неважлио зовсім"),
    );

subtest "Error object" => {
    plan 2;

    my $try = 1;
    for @errParams -> %errParams {
        my $err = Cro::RPC::JSON::MethodResponse::Error.new( |%errParams );

        is-deeply $err.Hash, %errParams, "error object converted to hash {$try++}";
    }
}

subtest "Response object" => {
    plan 3;

    my $id = 1;

    for |(<error> X=> @errParams), result => {r1=>pi, r2=>"π"} -> $k {
        my $req = Cro::RPC::JSON::Request.new:
            request => Cro::HTTP::Request.new, # A mock is ok, it's not gonna be used.
            data => %(
                :$id,
                :jsonrpc("2.0"),
                :method<foo>,
                :params{},
            );

        my $payload = $k.key ~~ 'error'
            ?? :error( Cro::RPC::JSON::MethodResponse::Error.new( |$k.value ) )
            !! $k;

        my $resp = $req.jrpc-response: |$payload;
        is-deeply $resp.Hash, %(:$id, |$k, :jsonrpc("2.0")), "convertion to hash {$id++}" ;
    };
}

subtest "Error handling" => {
    plan 1;
    my $req = Cro::RPC::JSON::Request.new:
        request => Cro::HTTP::Request.new, # A mock is ok, it's not gonna be used.
        data => %(
            :id<42>,
            :jsonrpc("2.0"),
            :method<foo>,
            :params{},
        );
    throws-like {
            $req.jrpc-response: :result("the question"), :error( Cro::RPC::JSON::MethodResponse::Error.new( |@errParams[0] ));
        },
        X::Cro::RPC::JSON::ServerError,
        "use of both `result` and `error` keys in JSON-RPC response is prohibited";
}

done-testing;

# vim: ft=perl6


