<?php

namespace App\VehicleSpec\Jobs;

use App\Traits\MapsTaxonomies;
use App\VehicleSpec\Services\CapVehicleLookupService;
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\Facades\App;
use Illuminate\Support\Facades\Log;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\Notifications\Facades\Notification;

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

    private array $capFields = [
        'cap_id',
        'cap_code',
    ];

    public function __construct(
        protected readonly Vehicle $vehicle,
        protected bool $force = false
    ) {
        $this->onQueue('specs');
    }

    public function handle(): void
    {
        if (!$this->force && !empty($this->vehicle->cap_id)) {
            return;
        }

        $result = $this->capVehicleLookupService()->lookup($this->vehicle);

        if (!empty($result['cap_id'])) {
            $this->vehicle->newQuery()->where('id', $this->vehicle->id)->update($result);
            $this->vehicle->fill($result);
        } else {
            Notification::addNotification(
                'warning',
                'Could not find CAP ID in database of vehicles',
                [
                    $this->vehicle->registration_number,
                ],
                'edit-vehicles',
                "/manage-content/vehicles/edit/{$this->vehicle->id}",
            );
        }

        $this->storeUnmappedTaxonomy($this->vehicle);
    }

    public function failed(?\Throwable $exception): void
    {
        Log::error($exception->getMessage(), [
            'tenant' => tenant('id'),
            'vehicle' => $this->vehicle,
            'exception' => $exception,
        ]);
    }

    protected function getProviderName(): string
    {
        return 'cap_database';
    }

    protected function getDetailsForTaxonomyMap(array $record): array
    {
        return [
            'tenant_id' => tenant('id'),
            'registration_number' => $this->vehicle?->registration_number ?? '',
            'make' => $record['make_id'] ?? '',
            'model' => $record['model_id'] ?? '',
            'fuel_type' => $record['fuel_type_id'] ?? '',
            'transmission' => $record['transmission_id'] ?? '',
        ];
    }

    private function capVehicleLookupService(): CapVehicleLookupService
    {
        return App::make(CapVehicleLookupService::class);
    }
}
