use strict;
use warnings;
use Test::More 0.96;
use Test::Exception;

use WebService::KvKAPI;
use Sub::Override;
use Test::Mock::One;
use Test::Deep;

my $api = WebService::KvKAPI->new(
    api_key => 'foobar',
);

my @methods = qw(
    search
    profile
    api_call
    _build_open_api_client
);

foreach (@methods) {
    can_ok($api, $_);
}

my $client = $api->client;
isa_ok($client, "OpenAPI::Client");

my @openapi_operations = qw(
    Companies_GetCompaniesBasicV2
    Companies_GetCompaniesExtendedV2
);

foreach (@openapi_operations) {
    can_ok($client, $_);
}

my $override = Sub::Override->new(
    'OpenAPI::Client::WebService__KvKAPI_kvk_gsasearch_webapi__v1_json::Companies_GetCompaniesBasicV2' => sub {
        return Test::Mock::One->new(
            'X-Mock-Strict' => 1,
            error           => undef,
            res             => {
                json => \{
                    'foo' => 'bar',
                }
            },
        );
    },
);

my $answer = $api->api_call(
    'Companies_GetCompaniesBasicV2',
    { Bar => "baz" },
);

cmp_deeply($answer, { foo => 'bar' }, "Got the JSON response as a HashRef");

$override->replace(
    'OpenAPI::Client::WebService__KvKAPI_kvk_gsasearch_webapi__v1_json::Companies_GetCompaniesBasicV2' => sub {
        return Test::Mock::One->new(
            'X-Mock-Strict' => 1,
            error           => \{ message => 'Bad request' },
        );
    }
);

throws_ok(
    sub {
        $api->api_call('Companies_GetCompaniesBasicV2', { Bar => 'baz' });
    },
    qr/Error calling KvK API with operation 'Companies_GetCompaniesBasicV2': 'Bad request'/,
    "Error!"
);

done_testing;
