#!/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-02.sql';
logMessage( 'info', "Getting all vendors from $file" );
my $sth = Orchard::DB::Connect->prepare_file( $dbh, $file );
$sth->execute();

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

if ( $sth->rows() ) {
    while ( my $row = $sth->fetchrow_hashref('NAME_lc') ) {
        foreach my $k ( keys %{$row} ) {
            eval { JSON::XS::decode_json( $row->{$k} ) };
            next if $@;
            $row->{$k} = JSON::XS::decode_json( $row->{$k} );
        }
        #my $json = JSON::XS::encode_json($row);
        my $id   = $row->{'account_id'};
		my $file = "output/$id.json";
		logMessage('info',"Create $file");
        my $fh   = FileHandle->new( $file, "w" );
        $fh->print($coder->encode($row));
        $fh->close;
    }
}
