#!/usr/bin/perl

use constant 'OUTDIR' => '/var/app/orchard/database/art_relations/build/changelog/dml';

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

use Git;
use JSON::XS;
use FileHandle;
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;
use Orchard::DB::Connect;

my $db = 'abacusprod';
logMessage( 'info', "Connecting to $db" );
my $dsn = Orchard::DB::Connect->dsn($db);
my $dbh;
if ( defined $dsn->{'ssh'} ) {
    my $ssh = $dsn->{'ssh'};
    $ssh->{'net'}->spawn( $ssh->{'tunnel'} );
    sleep 1;
}
$dbh = DBI->connect( @{ $dsn->{'conn'} } ) || die "Conn: $DBI::errstr";
my $dbx = Orchard::Session::getdbx($db);

my $rset = $dbx->resultset('RoyaltyAccounting::PaymentGroupPaymentAccount')->search( {
        'payment_group_payment_id' => { '-in' => [ 16, 17 ] }
    }
);
while ( my $row = $rset->next ) {
    my $aref = JSON::XS::decode_json( $row->contracts_payable );
    foreach my $href ( @{$aref} ) {
		my $id = $row->payment_group_payment_id;
        my $line = csv_build( ( $id, $row->account_id, $href->{'contract_id'}, $row->currency_code, $href->{'current_balance'} ) );
        print "$line\n";
    }
}
