<?php

namespace App\Modules\Leasing\Jobs;

use App\Facades\Settings;
use Exception;
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\Collection;
use Illuminate\Support\Facades\Log;
use Mtc\MercuryDataModels\VehicleMake;
use Mtc\MercuryDataModels\VehicleModel;

abstract class BaseImportJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    protected float $vat_rate = 0;
    protected array $vehicle_makes = [];
    protected array $vehicle_models = [];

    abstract protected function importItem(array $item);

    public function __construct(
        protected Collection $data
    ) {
        $this->onQueue('leasing-sync');
        $this->vat_rate = 1.00 + Settings::get('leasing-keyloop-fleet-kompact-vat-rate', 0);
    }

    public function handle()
    {
        $this->data->each(function ($item) {
            try {
                $this->importItem($item);
            } catch (Exception $exception) {
                Log::error('Failed to import lease data batch', [
                    'message' => $exception->getMessage(),
                    'file' => $exception->getFile(),
                    'tenant' => tenant('id'),
                ]);

                // Avoid potentially logging hundreds of exceptions.
                // Break out of the ->each() to stop processing this batch.
                return false;
            }
        });
    }

    protected function getVehicleMake(string $make_code): ?int
    {
        if (!array_key_exists($make_code, $this->vehicle_makes)) {
            $this->vehicle_makes[$make_code] = VehicleMake::query()
                ->where('keyloop_id', '=', $make_code)
                ->first()
                ?->id;
        }

        return $this->vehicle_makes[$make_code];
    }

    protected function getVehicleModel(string $model_code, string $make_code): ?int
    {
        if (!array_key_exists($make_code, $this->vehicle_models)) {
            $this->vehicle_models[$make_code] = [];
        }

        if (!array_key_exists($model_code, $this->vehicle_models[$make_code])) {
            $this->vehicle_models[$make_code][$model_code] = VehicleModel::query()
                ->where('keyloop_id', '=', $model_code)
                ->first()
                ?->id;
        }

        return $this->vehicle_models[$make_code][$model_code];
    }
}
