#!/usr/bin/env perl

# Example script showing how to use WebService::NetSuite::SuiteTalk.
# Most of it is concerned with loading configuration options
# from suitetalk.ini using Config::Any or environment variables.

use Modern::Perl '2010';    ## no critic (Modules::ProhibitUseQuotedVersion)
use Config::Any;
use CHI;
use File::Temp;
use FindBin '$Bin';
use WWW::Mechanize::Cached;
use WebService::NetSuite::SuiteTalk;

# load configuration from suitetalk.[cnf|conf|ini|json|jsn|pl|perl|xml|ym|yaml]
my %configuration = %{ Config::Any->load_stems(
        {   stems           => ["$Bin/suitetalk"],
            flatten_to_hash => 1,
            use_ext         => 1,
        },
    ),
};
%configuration = map { %{ $configuration{$_} } } keys %configuration;

# default to File cache in temporary directory, but can be overridden by config
my $tempdir;
if ( 'File' eq $configuration{Cache}{driver}
    and not $configuration{Cache}{root_dir} )
{
    $tempdir = File::Temp->newdir;
    $configuration{Cache}{root_dir} = "$tempdir";
}
my $user_agent = WWW::Mechanize::Cached->new(
    cache => CHI->new( driver => 'File', %{ $configuration{Cache} } ) );

# NETSUITE_* environment variables can override configuration file
$configuration{Connection} = {
    %{ $configuration{Connection} },
    (   map { ( $_ => $ENV{"NETSUITE_\U$_"} ) }
            grep { $ENV{"NETSUITE_\U$_"} }
            qw(account_id email_address password endpoint)
    ),
};

# create the connection
my $suitetalk = WebService::NetSuite::SuiteTalk->new(
    user_agent => $user_agent,
    xsi_auto   => 1,
    %{ $configuration{Connection} },
);

# report the server time
my $answer_ref = $suitetalk->getServerTime;
if ( $answer_ref->{parameters}{getServerTimeResult}{status}{isSuccess} ) {
    say $answer_ref->{parameters}{getServerTimeResult}{serverTime};
}
