<?php

namespace App\Modules\Leasing\Jobs;

use App\Facades\Settings;
use App\TaxonomyMap;
use App\Traits\MapsTaxonomies;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Str;
use Mtc\MercuryDataModels\KeyloopLeaseVehicleVariant;

class MapFuelTypesJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;
    use MapsTaxonomies;

    public function handle()
    {
        $fuel_hint_spec_option_code = Settings::get('leasing-keyloop-fleet-kompact-hybrid-fuel-hint-option-code');

        // fetch variants which have no fuel type but which have the fuel hint spec option
        $variants = KeyloopLeaseVehicleVariant::query()
            ->whereNull('fuel_type_id')
            ->whereHas('spec', fn ($query) =>
                $query->where('keyloop_lease_options.option_code', $fuel_hint_spec_option_code))
            ->get();

        $variants->each(function ($variant) use ($fuel_hint_spec_option_code) {
            // get the name of the spec option
            $spec_option_name = $variant->spec
                ?->filter(fn ($item) => $item->option_code == $fuel_hint_spec_option_code)
                ?->first()
                ?->name ?? '';

            // check if the spec option gives a clue about the hybrid fuel type
            if (Str::contains($spec_option_name, 'petrol', true)) {
                $variant->update([
                    'fuel_type_id' => $this->getMappedTaxonomy(
                        TaxonomyMap::FUEL_TYPE,
                        'Petrol Hybrid',
                    )
                ]);
            } elseif (Str::contains($spec_option_name, 'diesel', true)) {
                $variant->update([
                    'fuel_type_id' => $this->getMappedTaxonomy(
                        TaxonomyMap::FUEL_TYPE,
                        'Diesel Hybrid',
                    )
                ]);
            }
        });
    }

    protected function getProviderName(): string
    {
        return 'keyloop-fleet-kompact';
    }
}
