<?php

namespace App\Modules\Leasing\Jobs;

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

class ImportOptionPriceJob extends BaseImportJob
{
    protected function importItem(array $item)
    {
        switch (strtoupper($item['option-code'])) {
            case 'VARIANTPRICE':
                $this->setVariantPrice($item);
                break;
            case 'DELIVERYPRICE':
                $this->setDeliveryPrice($item);
                break;
            default:
                $this->upsertOptionPrice($item);
                break;
        }
    }

    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'],
        ]);
    }
}
