package BookPub::Import::Importer::BoksalaStudenta::v4;

use strict;

use lib '/app/tools/bookpub/lib';
use base 'BookPub::Import::Importer';

use Date::Calc qw(Days_in_Month);

sub _fieldMap {
    {
        dateBegin          => 'A2',
        rTitle             => 'C',
        rIsbn13            => 'B',
        countryCode        => 'J',
        rUnits             => 'H',
        rListPrice         => 'F',
        rListPriceCurrency => 'B7',
        rDiscount          => 'I',
        rRevenue           => 'K',
        currencyCode       => 'B7',
    }
}

sub _headerIdentifier { ( rIsbn13 => 'ISBN' ) }
sub _useIsSaleRec { 1 }

sub rPurchaseType      { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub purchaseType       { shift->rPurchaseType() }
sub rListPriceCurrency { shift->currencyCode() }
sub productType        { BookPub::DB::Item::Sale::kProductTypeEBook }
sub rProductType       { BookPub::DB::Item::Sale::kProductTypeEBook }
sub priceType          { 'rrp' }
sub rPriceType         { 'rrp' }
sub rServiceName       {'Boksala studenta'}

sub rListPrice         {
    my $self = shift;

    my $listPrice = $self->_getByFieldName('rListPrice') || 0;
    return $listPrice =~ s/[^0-9\.]//gr;
}

my %months = (
    january   => 1,
    february  => 2,
    march     => 3,
    april     => 4,
    may       => 5,
    june      => 6,
    july      => 7,
    august    => 8,
    september => 9,
    october   => 10,
    november  => 11,
    december  => 12,
);

sub dateBegin {
    my $self = shift;

    my $date = $self->_getByFieldName('dateBegin') || '';

    # Monthly Sales Report for January 2024
    my ($m, $y) = $date =~ /(\w+?) (\d{4})/i;
    if ( exists $months{lc($m)} ) {
        $m = $months{lc($m)};
        return (sprintf "%04d-%02d-%02d", $y, $m, 1);
    }

    $self->fail("Unable to determine date begin from: $date");
}

sub dateEnd {
    my $self = shift;

    my $date = $self->_getByFieldName('dateBegin') || '';

    # Monthly Sales Report for January 2025
    my ($m, $y) = $date =~ /(\w+?) (\d{4})/i;
    if ( exists $months{lc($m)} ) {
        $m = $months{lc($m)};
        return sprintf("%04d-%02d-%02d", $y, $m, Days_in_Month($y, $m));
    }

    $self->fail("Unable to determine date end from: $date");
}

sub rUnitPrice {
    my $self = shift;

    return $self->rRevenue() / $self->rUnits() if $self->rUnits();
}

sub isFree {
    my $self = shift;

    return !$self->rRevenue && $self->rUnits ? 'Y' : 'N';
}

sub _isSaleRec {
    my $self = shift;

    my $country = $self->_getByFieldName("countryCode") || "";

    return 0 if ($country =~ /total/i);

    return $self->SUPER::_isSaleRec();
}

1;
