#!/usr/bin/perl

use constant 'OUTDIR' => 'royalty_accounting';

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

use JSON::XS;
use FileHandle;
use Array::Utils qw/:all/;
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;
use Orchard::Accounting::JIRA;
use Orchard::ETL::Extract::CSV;

my ( $opt, $usage ) = describe_options(
    '%c %o <some-arg>',
    [ 'help|?|h'        => "print usage message and exit" ],
    [ 'file|f=s'        => 'File to parse',                                     { 'required' => 1 } ],
    [ 'git_version|v=i' => 'git tree version <ACC>-<1234>-<VERSION> default 1', { 'default'  => 1 } ],
);
if ( $opt->help ) {
    logMessage( 'info', $usage->text, 'options' );
    exit 1;
}

my ($jira_ticket) = $opt->file =~ m!.*?/ACC(....)/.*$!;

my $jira     = Orchard::Accounting::JIRA->new( $jira_ticket, $opt->git_version, OUTDIR );
my $branch   = $jira->branch;
my $filename = $jira->getfilepath("new_contributions");

my $ttlContributions;
my $ttlContractTerms;
my $terms;
my $seen = { 'contract_id' => 'contribution_id' };
my $tsv  = Orchard::ETL::Extract::CSV->new( $opt->file );
while ( my $row = $tsv->getrow() ) {
    next if defined $tsv->getcol( $row, 'J' );

    my $ctid = $tsv->getcol( $row, 'F' );
    next if not defined $ctid;

    my $cnid = $tsv->getcol( $row, 'G' );

    ## make sure contribution is unique to term
    next if exists $seen->{$ctid}->{$cnid};
    $seen->{$ctid}->{$cnid}++;

    $ttlContributions++;

    push @{ $terms->{$ctid} }, $cnid;
}

$ttlContractTerms = scalar keys %{$terms};

my $inids = join ',', sort keys %{$terms};

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

-- changeset jgetter:1

DROP TABLE IF EXISTS `ROLLBACK-DATA-${branch}`;

CREATE TABLE `ROLLBACK-DATA-${branch}`
SELECT ct.* FROM contract_term ct WHERE ct.contract_term_id IN (
$inids
);

!

foreach my $id ( sort keys %{$terms} ) {
    my $list = JSON::XS::encode_json( $terms->{$id} );
    my $sql;
    $sql  .= "UPDATE contract_term SET last_modified_by='${branch}',last_modified=NOW(),\n";
    $sql  .= "attachments=JSON_MERGE_PRESERVE(attachments,'$list')\n";
    $sql  .= "WHERE contract_term_id=$id;\n\n";
    $body .= $sql;
}

$body = <<"!";
$body
--rollback UPDATE contract_term ct
--rollback JOIN `ROLLBACK-DATA-${branch}` rb USING (contract_term_id)
--rollback SET ct.attachments=rb.attachments;
!

$jira->printfile( $filename, $body );
$jira->showfile($filename);

logMessage( 'info', "Total contributions: $ttlContributions" );
logMessage( 'info', "Total contract terms: $ttlContractTerms" );
