package RPS::Sale::Match::RazorAndTie;

use strict;
use warnings;

use base 'RPS::Sale::Match';

use lib '/app/tools/data_classes/lib';
use File::Sale;

sub new {
    my ( $self, $parent ) = @_;
    return undef unless ( ref($parent) eq 'HASH' );

    return bless $parent;
}

sub FindBestMatch {
    my $self = shift;
    my %in   = @_;

    if (   $in{data}->{outlet}
        && $in{data}->{outlet} =~ m/datapak/i
        && $in{data}->{client_product_id}
        && $in{data}->{product_type} eq File::Sale::TYPE_CD ) {
        my $result;
        if ( my $product_id = $self->_catalog_match( $in{data} ) ) {
            $result = new RPS::Sale::Match::Result(
                products        => [$product_id],
                num_products    => 1,
                import_status   => 1,
                map_id          => undef,
                rec_products    => undef,
                search_products => [],
                detail          => undef,
            );
        } else {
            $result = new RPS::Sale::Match::Result(
                products        => [],
                num_products    => 0,
                import_status   => 2,
                map_id          => undef,
                rec_products    => [],
                search_products => undef,
                detail          => [],
            );
        }
        return $result;
    } else {
        my $result = $self->SUPER::FindBestMatch(@_);
        return $result;
    }
}

sub _catalog_match {
    my ( $self, $data ) = @_;

    my $sql = "SELECT product_id FROM product JOIN album ON asset_id=album_id " . "WHERE product_type_id = ? AND catalog_number = ?";
    my $sth = $self->dbh()->prepare($sql);
    $sth->execute( $data->{product_type}, $data->{client_product_id} );

    my $product_id;
    if ( $sth->rows() == 1 ) {
        $product_id = $sth->fetchrow_arrayref()->[0];
    }

    return $product_id;
}

1;

