#!/usr/bin/perl

=encoding UTF-8
=cut

=head1 DESCRIPTION

=cut

# common modules
use feature 'say';
use Carp;

# project modules
use lib::abs qw(
  ../../lib
  );
use qbit;
use Application;
use Exception::DB;

# global vars
use PiConstants qw(@BLOCKS_WITH_BRANDS);

# subs

# main
sub main {
    my $app = Application->new();
    $app->pre_run();

    $app->set_cur_user({id => 0});
    no strict 'refs';
    no warnings 'redefine';
    *{'QBit::Application::check_rights'} = sub {TRUE};

    $app->partner_db->init_db();
    my $dbh = $app->partner_db->get_dbh();

    print "{block_accessor} -- {block_page_id} -- {block_id} -- {block_brands}\n";
    foreach my $block_accessor (@BLOCKS_WITH_BRANDS) {
        my $page_id_field_name = $app->$block_accessor->get_page_id_field_name();

        my $sth = $dbh->prepare(
"SELECT `id`, `brands`, `$page_id_field_name` FROM `$block_accessor` WHERE `brands` != '[]' AND `brands` != 'NULL' AND `brands` IS NOT NULL"
          )
          or do {
            my $err_code = $dbh->err();
            throw Exception::DB $dbh->errstr() . " ($err_code)\n", errorcode => $err_code;
          };

        $sth->execute() or do {
            my $err_code = $sth->err();
            throw Exception::DB $sth->errstr() . " ($err_code)\n", errorcode => $err_code;
        };

        my $data = $sth->fetchall_arrayref({});

        foreach my $block (@$data) {
            print "$block_accessor -- $block->{$page_id_field_name} -- $block->{id} -- $block->{brands}\n";
            $app->partner_db->transaction(
                sub {
                    my $brands = from_json($block->{brands} // '[]');

                    $sth = $dbh->prepare(
"REPLACE INTO `brands` (`bid`, `block_id`, `page_id`, `blocked`, `cpm`) VALUES (?, $block->{id}, $block->{$page_id_field_name}, ?, ?)"
                      )
                      or do {
                        my $err_code = $dbh->err();
                        throw Exception::DB $dbh->errstr() . " ($err_code)\n", errorcode => $err_code;
                      };

                    if (@$brands) {
                        my (@bid, @blocked, @cpm);
                        foreach (@$brands) {
                            $_->{cpm} = undef if $_->{blocked} == 1;
                            push @bid,     $_->{bid};
                            push @blocked, $_->{blocked};
                            push @cpm,     $_->{cpm};
                        }

                        my $tuples =
                          $sth->execute_array({ArrayTupleStatus => \my @tuple_status}, \@bid, \@blocked, \@cpm);

                        if ($tuples) {
                            print "Successfully replaced $tuples records\n";
                        } else {
                            for my $tuple (0 .. @bid - 1) {
                                my $status = $tuple_status[$tuple];
                                $status = [0, "Skipped"] unless defined $status;
                                next unless ref $status;
                                throw Exception::DB sprintf
                                  "Failed to replace (%s, $block->{id}, $block->{$page_id_field_name}, %s, %s): %s\n",
                                  $bid[$tuple], $blocked[$tuple], $cpm[$tuple] // 'NULL', $status->[1];
                            }
                        }
                    }
                }
            );
        }
    }

    warn "#END\n";

    $app->post_run();
}
main();
__END__
