use strict;
use lib '/app/tools/common/lib';
use lib '/app/tools/bookpub/lib';

use Data::Dumper;
use Common::RSApp;
use BookPub::DB::Item::BookProduct;
use BookPub::DB::Item::Product;
use BookPub::DB::Item::Sale;

my $app = Common::RSApp->new( clientID => 308 );    # 308 == Hachette

my @isbnList;

# Read in all the ISBN values first.
#
while ( my $line = <STDIN> ) {
    chomp $line;
    my ( $isbn, $otherStuff ) = split( "\t", $line );
    push @isbnList, $isbn;
}

my %problemProducts;
foreach my $isbn (@isbnList) {
    print "ISBN: $isbn\n";

    my $bookProduct = BookPub::DB::Item::BookProduct->Lookup( isbn13 => $isbn );
    die "ERROR - unable to find product with isbn13=$isbn" unless $bookProduct;

    print "   product_id:" . $bookProduct->product_id . "\n";

    # Any sales mapped to this product?
    #
    my $c = BookPub::DB::Item::Sale->GetAllByProductID( $bookProduct->product_id );
    if ( 0 != $c->size() ) {
        $problemProducts{ $bookProduct->product_id }{bookProduct} = $bookProduct;
        $problemProducts{ $bookProduct->product_id }{numSales}    = $c->size();
    } else {

        # Not a 'problem' product, so we can in theory go ahead and blow it away.
        #
        my $product = BookPub::DB::Item::Product->Lookup( product_id => $bookProduct->product_id );
        $product->delete();
        $bookProduct->delete();
    }
}

foreach my $productID ( keys %problemProducts ) {
    print "product_id $productID:  sale count: " . $problemProducts{$productID}{numSales} . "\n";
}
