#!/usr/bin/perl

use strict;
use warnings;

use Date::Calc;
use Data::Dumper;
use Getopt::Std;

use constant 'MAXBULKLOAD' => 10000;

use lib '/app/tools/common/lib';
use Common::RSDB;
use Common::Logger;
use Common::Stats::DTMVBuilder;
use Common::Consts qw(%CLIENT_SALE_AGG);

$| = 1;

open( STDERR, ">>/app/data/logs/sale_report/bookstats.log" ) unless ( -t STDIN && -t STDOUT );

logMessage( 'info', "running with args: " . join( ',', @ARGV ) );

my %opt;
getopts( 'c:f', \%opt );

my $client_id     = $opt{c};
my $force_rebuild = $opt{f};

unless ( $client_id =~ /^\d+$/ && $client_id > 0 ) {
    die usage("client_id '$client_id' must be a number greater than zero");
}

logMessage( 'info', "client_id = $client_id" );

# good_sale_min is the minimum threshold of good sale records to total records
# for a file to be included in the sales aggregates. It should be specified as
# a percentage out of 100. See the sub load_stage_table for the definition of
# "good" sale record.
my $good_sale_min = $CLIENT_SALE_AGG{$client_id}->{good_sale_min};

unless ( $good_sale_min >= 1 && $good_sale_min <= 100 ) {
    die "The 'good_sale_min' value specified in \%Common:Consts:CLIENT_SALE_AGG must be percentage between 1 and 100\n";
}

my $builder   = Common::Stats::DTMVBuilder->new(
 	Common::RSDB->new( client_id => $client_id, dbi_attr => { RaiseError => 1 } )
);

logMessage( 'info', "fetching sales data from ". $builder->schema );

my $sale_data = $builder->get_sale_data;
my $tables_rebuilt = 0;
if ( $force_rebuild || $builder->sale_data_has_changed( $sale_data ) ) {
    $builder->rebuild_aggregates($good_sale_min);
    $tables_rebuilt = 1;
}
$builder->log_sale_data( $sale_data, $tables_rebuilt );
$builder->finish;

exit(0);
