<?php

namespace App\Modules\Leasing;

use App\Modules\Leasing\Jobs\VariantOptionMapImportJob;
use Illuminate\Support\Collection;
use Mtc\MercuryDataModels\KeyloopLeaseVariantOptionMapping;
use Mtc\MercuryDataModels\KeyloopLeaseVehicleVariant;

class KeyloopFleetKompactVariantOptionMapImporter extends KeyloopFleetKompactImporterBase
{
    protected array $filtered_variants = [];

    protected function filter(Collection $data): bool
    {
        if (!isset($this->filtered_variants[$data['variant-code']])) {
            // only import items for variants that are present in the current import
            $this->filtered_variants[$data['variant-code']] = KeyloopLeaseVehicleVariant::query()
                ->where('was_recently_synced', '=', true)
                ->where('external_variant_id', '=', $data['variant-code'])
                ->exists();
        }
        return $this->filtered_variants[$data['variant-code']];
    }

    protected function prepareForImport(): void
    {
        KeyloopLeaseVariantOptionMapping::query()->update([
            'was_recently_synced' => false,
        ]);
    }

    protected function importItems(Collection $data): void
    {
        $this->dispatch(new VariantOptionMapImportJob($data->map(fn ($item) => [
            'external_variant_id' => $item['variant-code'],
            'make_id' => $this->getVehicleMake($item['franchise-code']),
            'model_id' => $this->getVehicleModel($item['model-code'], $item['franchise-code']),
            'option_type' => $item['option-type'],
            'option_code' => $item['option-code'],
            'option_availability_code' => $item['availability-code'],
        ])));
    }
}
