#!perl

use Modern::Perl '2010';    ## no critic (Modules::ProhibitUseQuotedVersion)
use Test::More tests => 1;
use Test::TempDir::Tiny;
use Benchmark;
use Const::Fast;
use CHI;
use List::Util 1.33 'all';
use WWW::Mechanize::Cached;
use WebService::NetSuite::SuiteTalk;

const my @NETSUITE_ENVIRONMENT => map {"PERL_TEST_NETSUITE_\U$_"}
    qw(account email password);

SKIP: {
    skip "set @NETSUITE_ENVIRONMENT environment variables to run this test", 1
        if not all { exists $ENV{$_} } @NETSUITE_ENVIRONMENT;

    my $cache_root = tempdir;
    my $user_agent = WWW::Mechanize::Cached->new(
        cache => CHI->new( driver => 'File', root_dir => $cache_root ) );
    note "Cache is in $cache_root";

    my %bench = map {
        ( $_ => timeit( 1, sub { new_suitetalk($user_agent) } ) )
    } qw(cold warm hot);
    my $bench_diff = timediff( @bench{qw(cold warm)} );

    cmp_ok( $bench_diff->real, '>', 0, 'warm cache faster than cold' );
    note 'Warm cache difference: ' => timestr($bench_diff);
    note 'Hot cache difference:  ' =>
        timestr( timediff( @bench{qw(warm hot)} ) );
}

sub new_suitetalk {
    my $user_agent = shift;
    return WebService::NetSuite::SuiteTalk->new(
        account_id    => $ENV{PERL_TEST_NETSUITE_ACCOUNT},
        email_address => $ENV{PERL_TEST_NETSUITE_EMAIL},
        password      => $ENV{PERL_TEST_NETSUITE_PASSWORD},
        user_agent    => $user_agent,
        xsi_auto      => 1,
    );
}
