<?php

namespace App\Modules\Leasing\Jobs;

use Mtc\MercuryDataModels\KeyloopLeaseResidualValue;

class ImportResidualValuesJob extends BaseImportJob
{
    private array $columns_to_ignore = [
        'fran',
        'model',
        'variant',
    ];

    // external codes for expected contract lengths
    private array $contract_lengths = [
        '1' => 12,
        '2' => 24,
        '3' => 36,
        '4' => 48
    ];

    // external codes for expected annual mileages
    private array $annual_mileages = [
        '01' => 5000,
        '02' => 10000,
        '03' => 15000,
        '04' => 20000,
        '05' => 25000,
        '06' => 30000,
        '07' => 35000,
        '08' => 40000,
        '09' => 45000,
        '10' => 50000,
        '11' => 55000,
        '12' => 60000,
    ];

    protected function importItem(array $item)
    {
        collect($item)
            ->filter(
                fn($column_value, $column_name)
                => !in_array($column_name, $this->columns_to_ignore) && strlen($column_name) >= 3
            )
            ->each(function ($column_value, $column_name) use ($item) {
                $contract_index = substr($column_name, 0, 1);
                $mileage_index = substr($column_name, 1, 2);

                // if we don't have options for the contract or mileage, skip this column
                if (
                    !array_key_exists($contract_index, $this->contract_lengths)
                    || !array_key_exists($mileage_index, $this->annual_mileages)
                ) {
                    return;
                }

                KeyloopLeaseResidualValue::query()->updateOrCreate([
                    'external_variant_id' => $item['variant'],
                    'contract_length' => $this->contract_lengths[$contract_index],
                    'annual_mileage' => $this->annual_mileages[$mileage_index],
                ], [
                    'residual_value_excluding_vat' => $this->getResidualValueExVat($column_value),
                    'residual_value_including_vat' => $column_value,
                    'was_recently_synced' => true,
                ]);
            });
    }

    private function getResidualValueExVat(float $residual_value_inc_vat): float
    {
        $residual_value_ex_vat = $residual_value_inc_vat / $this->vat_rate;
        return round($residual_value_ex_vat, 2);
    }
}
