#!/usr/bin/perl

use strict;
use warnings;
use open ':std', ':encoding(UTF-8)';

use JSON::XS;
use FileHandle;
use File::Find::Rule;
use Text::CSV::Easy(qw/csv_build csv_parse/);
use Getopt::Long::Descriptive(qw/describe_options/);

use lib '/var/app/orchard/collab/jgetter/perllib';
use Orchard::Session;

## connect to and set snowflake session to prod royalty accounting
my $dbh = Orchard::Session::getdbh('snowflake');
$dbh = Orchard::DB::Connect->snowflake_session( $dbh, { 'schema' => 'prod' } );

my $file = 'snowflake-view-query-03.sql';
logMessage( 'info', "Getting all vendors from $file" );
my $sth = Orchard::DB::Connect->prepare_file( $dbh, $file );
$sth->{'LongTruncOk'} = 1;
$sth->{'LongReadLen'} = 20000;

$sth->execute();

my $coder = JSON::XS->new->utf8->pretty->canonical->allow_nonref;

if ( $sth->rows() ) {
    while ( my $row = $sth->fetchrow_hashref('NAME_lc') ) {
        my $href;
        eval { $href = JSON::XS::decode_json( $row->{'body'} ) };
        next if $@;

        my $id   = $row->{'account_id'};
        my $file = "output/$id.json";
        logMessage( 'info', "Create $file" );
        my $fh = FileHandle->new( $file, "w" );
        $fh->print( $coder->encode($href) );
        $fh->close;
    }
}
