<?php

namespace App\Console\Commands;

use App\Facades\Settings;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Mtc\MercuryDataModels\Services\LocatingService;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleAttribute;

class FindVehicleCoordinates extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'vehicles:find-coordinates';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Find vehicle coordinates';


    public function __construct(private readonly LocatingService $service)
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        if (!$this->enabledForTenant()) {
            return Command::SUCCESS;
        }

        $fromAttribute = VehicleAttribute::query()->where('slug', 'postcode')->exists();

        Vehicle::query()->whereNull('lat')
            ->when(
                $fromAttribute,
                fn($query) => $query->with('attributeValues'),
                fn($query) => $query->with('dealership'),
            )
            ->chunk(150, fn(Collection $chunk) => $chunk
                ->each(fn(Vehicle $vehicle) => $this->locate($vehicle, $fromAttribute)));

        return Command::SUCCESS;
    }

    private function enabledForTenant(): bool
    {
        return Settings::get('automotive-vehicle-filters-postcode') === true;
    }

    private function locate(Vehicle $vehicle, bool $fromAttribute): void
    {
        if (!$fromAttribute) {
            $coords = explode(',', $vehicle->dealership?->coordinates ?? '');
            if (count($coords) == 2) {
                $vehicle->update([
                    'lat' => $coords[0],
                    'lng' => $coords[1],
                ]);
            }
            return;
        }

        $postcode = null;
        $postCodeAttribute = $vehicle->attributeValues->where('slug', 'postcode')->first();

        if (!empty($postCodeAttribute->value)) {
            $postcode = $postCodeAttribute->value;
        } elseif (!empty($postCodeAttribute->value_text)) {
            $postcode = $postCodeAttribute->value_text;
        }

        if (empty($postcode)) {
            return;
        }

        try {
            $location = $this->service->locate($postcode);
            if ($location->lat()) {
                $vehicle->update([
                    'lat' => $location->lat(),
                    'lng' => $location->lng(),
                ]);
            }
        } catch (\Exception $exception) {
            $this->output->error($exception->getMessage());
        }
    }
}
