#!/usr/bin/env perl
use v5.24;
use warnings;
use English '-no_match_vars';
use experimental 'signatures';
no warnings 'experimental::signatures';

use Test::More;
use Test::Exception;

eval { require Data::Resolver::Base; 1 }
  or BAIL_OUT 'cannot load base class';

use File::Basename 'dirname';
use lib dirname(__FILE__) . '/more_lib';    # DataResolverFakeAsset

subtest 'using the regular asset class' => sub {
   my $ar = Data::Resolver::Base->new;
   my $asset;
   lives_ok { $asset = $ar->asset(foo => raw => 'whatever') }
   'method asset()';
   isa_ok $asset, 'Data::Resolver::Asset';
   ok $asset->is_useable, 'asset is useable';
   is $asset->raw_data, 'whatever', 'contents of the asset';
};

subtest 'using a fake asset class' => sub {
   my $ar =
     Data::Resolver::Base->new(asset_class => 'DataResolverFakeAsset');
   my $asset;
   lives_ok { $asset = $ar->asset(foo => raw => 'whatever') }
   'method asset()';
   isa_ok $asset, 'DataResolverFakeAsset';
   is $asset->{raw}, 'whatever', 'arg to new: raw';
   is $asset->{key}, 'foo',      'arg to new: key';
};

subtest 'basic complaints' => sub {
   my $ar = Data::Resolver::Base->new;

   throws_ok { $ar->complain(418 => q{I'm a teapot}) }
   qr{\A\[418\] I'm a teapot at}, 'base is capable of complain-ing';

   throws_ok { $ar->not_found('bar') } qr{\A\[404\] Not Found: <bar> at },
     'not_found()';

   my $buffer = '';
   open my $fh, '<:raw', \$buffer or BAIL_OUT "open(): $OS_ERROR";

   my $asset;
   lives_ok { $asset = $ar->asset(foo => filehandle => $fh) }
   'method asset()';
   isa_ok $asset, 'Data::Resolver::Asset';
   ok $asset->is_useable, 'asset is useable';
   my $retake_fh = $asset->filehandle;
   ok !$asset->is_useable, 'asset is not useable any more';

   throws_ok { $asset->assert_useable }
   qr{\[400\] Not Useable at }, 'assert_useable throws some plain text';
};

subtest 'complaints via Ouch' => sub {
   plan skip_all => 'need Ouch for this test'
      unless eval { require Ouch; 1 };

   my $ar = Data::Resolver::Base->new(ouch => 1);

   throws_ok { $ar->complain(418 => q{I'm a teapot}) } 'Ouch',
   'base is capable of complain-ing, with Ouch';
   isa_ok $@, 'Ouch';
   is $@->code,    418,             'code from exception';
   is $@->message, q{I'm a teapot}, 'message from exception';

   my $buffer = '';
   open my $fh, '<:raw', \$buffer or BAIL_OUT "open(): $OS_ERROR";

   my $asset;
   lives_ok { $asset = $ar->asset(foo => filehandle => $fh) }
   'method asset()';
   isa_ok $asset, 'Data::Resolver::Asset';
   ok $asset->is_useable, 'asset is useable';
   my $retake_fh = $asset->filehandle;
   ok !$asset->is_useable, 'asset is not useable any more';

   throws_ok { $asset->assert_useable } 'Ouch',
   'assert_useable throws Ouch object';
   is $@->code,    400,           'code from exception';
   is $@->message, 'Not Useable', 'message from exception';
};

done_testing();
