#!/usr/bin/perl -Ilibs -I../www/libs

package API::ProductETA;

use strict;
use warnings;
use namespace::autoclean;

use Carp;
use Moose;
use Try::Tiny;

use ECS::Product;
use ECS::Site;

has '_data' => (
    'is'       => "ro",
    'isa'      => "Hash::MultiValue",
    'init_arg' => "data",
    'required' => 1,
    'handles'  => {
        'data' => "as_hashref",
    },
);

has '_params' => (
    'is'       => "ro",
    'isa'      => "Hash::MultiValue",
    'init_arg' => "params",
    'required' => 1,
    'handles'  => {
        'params' => "as_hashref",
    },
);

has '_site' => (
    'is'      => "ro",
    'isa'     => "ECS::Site",
    'lazy'    => 1,
    'default' => sub { ECS::Site::fromName( $ECS::Site::PRIMARY_SITE ) },
);

has '_dbh' => (
    'is'      => "ro",
    'isa'     => "DBI::db",
    'lazy'    => 1,
    'builder' => "_build__dbh",
);

has '_dbhr' => (
    'is'      => "ro",
    'isa'     => "DBI::db",
    'lazy'    => 1,
    'builder' => "_build__dbhr",
);

sub _build__dbh {
    shift->_site->estore_dbh;
}

sub _build__dbhr {
    shift->_site->estore_dbhr;
}

sub fetchMulti {
    my ( $self ) = @_;

    croak "Missing ids" unless     $self->data->{ 'ids' };
    croak "Invalid ids" unless ref $self->data->{ 'ids' } eq "ARRAY";
    my @productIDs = @{ $self->data->{ 'ids' } };

    my @products = ();
    for my $productID ( @productIDs ) {
        push @products, ECS::Product->new( {
            'dbh'       => $self->_dbh,
            'productID' => $productID,
        } );
    }
    
    ECS::Product::loadMulti( {
        'dbh'      => $self->_dbhr,
        'products' => \@products,
    } );

    my @results = ();
    for my $product ( @products ) {
        push @results, {
            'productId'   => $product->productID,
            'eta'         => $product->ETA,
            'name'        => $product->stockStatusShort,
            'description' => $product->stockStatusLong,
            'stockCount'  => $product->totalQtyAvailable,
        };
    }

    return \@results;
}

__PACKAGE__->meta->make_immutable;

1;

