<?php

namespace App\Modules\Leasing\Jobs;

use Mtc\MercuryDataModels\KeyloopLeaseOptionPrice;
use Mtc\MercuryDataModels\KeyloopLeaseVehicleVariant;

class ImportOptionPriceJob extends BaseImportJob
{
    protected function importItem(array $item)
    {
        match (strtoupper((string) $item['option-code'])) {
            'VARIANTPRICE' => $this->setVariantPrice($item),
            'DELIVERYPRICE' => $this->setDeliveryPrice($item),
            default => $this->upsertOptionPrice($item),
        };
    }

    private function setVariantPrice(array $item): void
    {
        KeyloopLeaseVehicleVariant::query()->where('external_variant_id', '=', $item['variant'])
            ->update([
                'price_ex_vat_ex_vrt' => $item['price-to-customer'],
                'price_inc_vat_ex_vrt' => $item['price-to-customer'] * $this->vat_rate,
                'vehicle_vrt' => $item['vrt'],
                'price_inc_vat_inc_vrt' => $item['incvatvrt'],
            ]);
    }

    private function setDeliveryPrice(array $item): void
    {
        KeyloopLeaseVehicleVariant::query()->where('external_variant_id', '=', $item['variant'])
            ->update([
                'delivery_ex_vat_ex_vrt' => $item['price-to-customer'],
                'delivery_inc_vat_ex_vrt' => $item['price-to-customer'] * $this->vat_rate,
                'delivery_vrt' => $item['vrt'],
                'delivery_inc_vat_inc_vrt' => $item['incvatvrt'],
            ]);
    }

    private function upsertOptionPrice(array $item): void
    {
        KeyloopLeaseOptionPrice::query()->updateOrCreate([
            'external_variant_id' => $item['variant'],
            'make_id' => $this->getVehicleMake($item['fran']),
            'model_id' => $this->getVehicleModel($item['model-code'], $item['fran']),
            'option_code' => $item['option-code'],
        ], [
            'was_recently_synced' => true,
            'price_ex_vat_ex_vrt' => $item['price-to-customer'],
            'price_inc_vat_inc_vrt' => $item['incvatvrt'],
            'vrt' => $item['vrt'],
        ]);
    }
}
