<?php

namespace App\Listeners;

use App\Events\NewVehicleImported;
use App\Facades\Feature;
use App\Facades\Settings;
use App\VehicleSpec\Jobs\VehicleCapIdLookup;
use App\VehicleSpec\Jobs\VehicleCapIdLookupViaDatabase;
use App\VehicleSpec\Jobs\VehicleCapIdLookupViaHPI;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Mtc\MercuryDataModels\Vehicle;

class VehicleCapIdLookupOnNewVehicleImport
{
    use DispatchesJobs;

    public function __construct()
    {
    }

    public function handle(NewVehicleImported $event): void
    {
        if (!$this->vehicleNeedsCapId($event->vehicle)) {
            return;
        }

        if ($this->localDatabaseLookupEnabled()) {
            $this->dispatch(new VehicleCapIdLookupViaDatabase($event->vehicle));
            return;
        }

        if ($this->hpiCapIdLookupEnabled()) {
            $this->dispatch(new VehicleCapIdLookupViaHPI($event->vehicle));
            return;
        }

        if ($this->capLookupEnabled()) {
            $this->dispatch(new VehicleCapIdLookup($event->vehicle));
        }
    }

    private function vehicleNeedsCapId(Vehicle $vehicle): bool
    {
        return empty($vehicle->cap_id);
    }

    private function localDatabaseLookupEnabled(): bool
    {
        return Feature::isEnabled('cap-database')
            && (Settings::get('cap-id-lookup-local-enabled') ?? false);
    }

    private function hpiCapIdLookupEnabled(): bool
    {
        return Settings::get('cap-id-lookup-hpi-enabled') ?? false;
    }

    private function capLookupEnabled(): bool
    {
        return Settings::get('vehicle-spec-providers-cap-enabled') ?? false;
    }
}
