#!/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;

eval {
    my $sql = (
        qq{
SELECT
    date_started,
    date_finished,
    max_date_modified,
    TIMESTAMPDIFF(SECOND,date_started,date_finished) ttc_seconds,
    total_records,
    total_records/TIMESTAMPDIFF(SECOND,date_started,date_finished) avg_rec_per_sec
FROM
    agg_sale_log
WHERE 1
    AND tables_rebuilt=1
ORDER BY 
    log_id DESC LIMIT 1
}
    );

    my $clients = Common::Session::getclients;

    my $dbx = Common::Session::getdbx('admindb');
    my $host = $dbx->resultset('Report::DDbHost')->search_related( 'aws_host', { 'is_production' => 1 } );

    while ( my $row = $host->next ) {
        my $dbh = Common::Session::getdbh( $row->hostname );
        my $sth = $dbh->prepare($sql);
        foreach my $client ( @{ $clients->by_host->{ $row->hostname } } ) {
            my $ddb = $dbx->resultset('Report::DDb')->search( { 'db_name' => $client->dbname } )->first;
            next unless defined $ddb;
            $dbh->do( "use " . $client->dbname );
            $sth->execute;
            if ( $sth->rows ) {
                my $href = { %{ $sth->fetchrow_hashref } };
                $href->{'d_db_id'} = $ddb->d_db_id;
                $dbx->resultset('Report::FStatReport')->update_or_create( $href, { 'key' => 'primary' } );
            }
        }
    }
};
if ($@) {
    logMessage( 'fatal', $@ );
}
