#!/usr/bin/perl

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

use JSON::XS;
use FileHandle;
use Text::CSV::Easy(qw/csv_build csv_parse/);

use lib '/app/tools/common/lib';
use Common::Session;
use Common::ProgressBar;

my $dbx = Common::Session::getdbx('admindb');
my $sql = (
    qq{
SELECT
	artist_payee_id,
	`name` artist_payee_name,
	lower(email) email,
	`status`+1 payee_status,
	date_created payee_created
FROM
	artist_payee
WHERE 1
	AND length(email)
}
);

my $clients = Common::Session::getclients;
foreach my $host ( sort keys %{ $clients->by_host } ) {

    my $dbh = Common::DB::Connect->connect($host);

    my $db_host = $dbx->resultset('Report::DDbHost')->search_related( 'aws_host', { 'hostname' => $host } )->first;
    next unless $db_host;

    my $hid = $db_host->db_host->d_db_host_id;

    foreach my $c ( @{ $clients->by_host->{$host} } ) {
        next unless $c->client_type eq 'RPS';

        my $ddb = $dbx->resultset('Report::DDb')->search( { 'd_db_host_id' => $hid, 'db_name' => $c->dbname } )->first;
		next unless defined $ddb;

        $dbh->do( "USE " . $c->dbname );
        my $rows = $dbh->selectall_hashref( $sql, 'artist_payee_id' );

        my $bar = Common::ProgressBar->new( scalar keys %{$rows}, "$host:".$c->dbname );

        foreach my $id ( sort keys %{$rows} ) {
            my $row = { %{ $rows->{$id} } };
            $row->{'d_db_id'} = $ddb->d_db_id;
            my $ins = $dbx->resultset('Report::DArtistPayee')->find_or_create( $row, { 'key' => 'uidx_d_db_id_a_payee_id' } );
            $bar->update;
        }

        $bar->finish;
    }
}
