<?php

namespace App\Modules\Leasing;

use App\Modules\Leasing\Jobs\ImportResidualValuesJob;
use Illuminate\Support\Collection;
use Mtc\MercuryDataModels\KeyloopLeaseResidualValue;
use Mtc\MercuryDataModels\KeyloopLeaseVehicleVariant;

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

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

        return $this->filtered_variants[$data['variant']];
    }

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

    /**
     * We expect each incoming row to contain all residual values.
     * Columns are expected to be named with a code representing the contract length
     * and annual mileage for the residual value.
     *
     * @param Collection $data
     * @return void
     */
    protected function importItems(Collection $data): void
    {
        $this->dispatch(new ImportResidualValuesJob($data->map(fn ($item) => $item->toArray())));
    }
}
