<?php

namespace App\Modules\Leasing\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Mtc\MercuryDataModels\KeyloopLeaseVehicleVariant;

class FlagCheapestVariantsJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public function handle()
    {
        // get model IDs
        $model_ids = KeyloopLeaseVehicleVariant::query()->groupBy('model_id')->pluck('model_id');

        // reset cheapest for all in stock models
        KeyloopLeaseVehicleVariant::query()
            ->whereIn('model_id', $model_ids)
            ->update([
                'is_cheapest_variant' => false,
            ]);

        $model_ids->each(function ($model_id) {
            // find cheapest variant with this model and mark as cheapest
            $cheapest_variant = KeyloopLeaseVehicleVariant::query()
                ->where('model_id', $model_id)
                ->where('cheapest_monthly_price_ex_vat', '>', 0)
                ->orderBy('cheapest_monthly_price_ex_vat')
                ->first();

            if ($cheapest_variant) {
                $cheapest_variant->update([
                    'is_cheapest_variant' => true,
                ]);
            }
        });
    }
}
