#!/usr/bin/perl

use constant 'INDIR'  => '/Users/jgetter/JIRA-Attachments';
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 DateTime;
use JSON::XS;
use FileHandle;
use Text::CSV::Easy(qw/csv_build csv_parse/);
use Getopt::Long::Descriptive(qw/describe_options/);

my ( $opt, $usage ) = describe_options(
    '%c %o <some-arg>',
    [ 'git_version|g=i' => 'git tree version <ACC>-<1234>-<VERSION> default 1', { 'default' => 1 } ],
    [ 'help|?|h'        => "print usage message and exit" ],
    [ 'infile|f=s'      => 'File to parse default ACC9999/UPCs.csv', { 'default' => 'UPCs.csv' } ],
    [ 'jira_id|j=i'     => 'JIRA ticket number', { 'required' => 1 } ],
    [ 'label_id|l=i'    => 'Label/Vendor ID - required', { 'required' => 1 } ],
    [ 'percent|p=i'     => 'Split percentage enter whole will convert decimal' ],
);

my $dir     = 'ACC' . $opt->jira_id;
my $ticket  = 'ACC-' . $opt->jira_id;
my $branch  = $ticket . '-' . $opt->git_version;
my $labelId = $opt->label_id;

my $percent;
if ( defined $opt->percent ) {
    $percent = sprintf( "%.2f", ( $opt->percent / 100 ) );
}

my $table  = '`ROLLBACK-DATA-' . $dir . '`';
my $infile = INDIR . "/" . $dir . "/" . $opt->infile;

my $sql = <<"!";
-- liquibase formatted sql

-- changeset jgetter:1

CREATE TABLE $table AS
SELECT ai.vendor_id,r.upc
FROM 
	art_relations.releases r
JOIN
	art_relations.artist_info ai ON r.artist_id=ai.artist_id
WHERE 1
	AND ai.vendor_id = $labelId
	AND r.upc IN (
!

my $fh = FileHandle->new( $infile, 'r' ) || die "No such file $infile";
my $data;
my $inserts;
my $i = 1;
while (<$fh>) {
    chomp;
    my ( $upc, $percnt ) = split ',', $_;
    $percnt = defined $percnt ? $percnt : $percent;
    die "Percent is required" unless defined $percnt;
    my $text = sprintf( "%15s", $upc );
    if ( $i++ % 6 == 0 ) {
        push @{$data}, $text;
        my $line = join ",", @{$data};
        $sql .= "$line,\n";
        undef $data;
    } else {
        push @{$data}, $text;
    }
    push @{$inserts}, [ $upc, $percnt ];
}
$fh->close;
my $line = join ",", @{$data};

$sql .= $line;
$sql .= <<"!";
);


!

my $insertSql = "INSERT INTO product_split (vendor_id,product_id,product_split_rate)";
foreach my $aref ( @{$inserts} ) {
    $sql .= "$insertSql\nSELECT vendor_id,upc,$aref->[1] FROM $table WHERE vendor_id=$labelId AND upc=$aref->[0];\n\n";
}

$sql .= <<"!";

--rollback DELETE ps.* FROM product_split ps JOIN $table rb WHERE rb.upc=ps.product_id AND rb.vendor_id=ps.vendor_id;
--rollback DROP TABLE $table;

!

my $repo = Git->repository(OUTDIR);

my $currentBranch = $repo->command( 'rev-parse', '--abbrev-ref', 'HEAD' );
chomp($currentBranch);
if ( $currentBranch ne $branch ) {
    print "Need to create " . OUTDIR . " branch [$branch] - current branch is $currentBranch\n";
    exit;
}

my $outfile = OUTDIR . "/${ticket}_bulk_load_product_splits_" . $opt->git_version . ".sql";

print "Creating file $outfile\n";

my $ofh = FileHandle->new( $outfile, 'w' );
$ofh->print($sql);
$ofh->close;

map { print "$_\n", } $repo->command('status');
