#!/usr/bin/perl

use strict;
use warnings;

package API::Product::Search;

use API::Config;

use lib $API::Config::Config->{'Website_libs'};

use ECS::DB;
use ECS::dbConfig;
use ECS::Product;
use ECS::Search::Product;

return 1;

# Searches product.description
# Returns array of hashes with keys: productID, descripion
# Returned array is sorted by search result score
sub description {
	my $class = shift;
	my $input = shift;
	
	my $response = {
		'success'   => 1,
		'error'     => undef,
		'update_DB'	=> $API::Config::Config->{'update_DB'}
	};
	
	my $search_query = $input->{'searchQuery'};
	
	unless ($search_query) {
		$response->{'success'} = 0;
		$response->{'error'} = 'searchQuery is required';
		return $response;
	}
	
	if (length($search_query) < 3) {
		$response->{'success'} = 0;
		$response->{'error'} = 'searchQuery requires at least 3 characters';
		return $response;
	}
	
	my @search_words = ();
	while ($search_query =~ m!"([^"]*)"|([^\s]+)\s*!g) {
		push(@search_words, $+);
	}
	
	my $result_productIDs = ECS::Search::Product::searchDescription1({
		'words'  => \@search_words,
		'limit'  => 2500,
	});
	
	unless (@{ $result_productIDs }) {
		$response->{'data'} = [];
		return $response;
	}
	
	my $dbhr = ECS::DB->connect({'config' => $ECS::dbConfig::db{'mysqlSlave'}, readonly => 1});
	my $dbh = ECS::DB->connect({'config' => $ECS::dbConfig::db{'mysql'}});
	
	my @products = map { ECS::Product->new({
		'dbh'       => $dbhr,
		'productID' => $_
	}) } @{ $result_productIDs };
	
	ECS::Product::loadMulti({
		'dbh'      => $dbhr,
		'products' => \@products,
	});
	
	# Extract specific data from each product
	$response->{'data'} = [map {{
		'productID'   => $_->productID,
		'partnumber'  => $_->partnumber,
		'description' => $_->description,
	}} @products];
	
	return $response;
}
