package Sale::Match::Koch;

use strict;
use warnings;

use base 'Sale::Match';

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

    return bless $parent;
}

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

    my $result = $self->SUPER::FindBestMatch(@_);

    if ( $in{skip_rec} && ( !$result || $result->NumProducts != 1 ) ) {
        if ( my $product_id = $self->_clean_match( $in{data} ) ) {
            Sale::Match::DEBUG && print STDERR "koch-match $in{data}->{track} $in{data}->{isrc} to $product_id\n";

            $result = new Sale::Match::Result(
                products        => [$product_id],
                num_products    => 1,
                import_status   => Sale::Match::STATUS_MATCH,
                map_id          => undef,
                rec_products    => undef,
                search_products => [],
                detail          => $result ? $result->Detail : undef,
            );
        }
    }

    if ( defined $result ) {
        return $result;
    } else {
        $self->{errstr} = "Could not return results!";
        return undef;
    }
}

sub _clean_match {
    my ( $self, $record ) = @_;
    return unless ( $record->{artist} && length $record->{album} && length $record->{track} );

    my $sql = qq|
SELECT product_id
FROM product_catalog_extract
WHERE artist_clean=? and album_clean=? and track_clean=?
|;
    my $sth = $self->dbh()->prepare($sql);
    $sth->execute(
        Common::Util::clean( $record->{artist} ),
        Common::Util::clean( $record->{album} ),
        Common::Util::clean( $record->{track} )
    );

    return $sth->fetchrow_arrayref()->[0] if ( $sth->rows() == 1 );
    return undef;
}

1;

