<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\Services\LocatingService;

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

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


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

    /**
     * Execute the console command.
     */
    public function handle()
    {
        Dealership::query()
            ->whereNotNull('postcode')
            ->where(fn ($query) => $query->whereNull('coordinates')->orWhere('coordinates', ''))
            ->get()
            ->each(fn (Dealership $dealership) => $this->locate($dealership));

        return Command::SUCCESS;
    }

    private function locate(Dealership $dealership): void
    {
        try {
            $this->service->locate($dealership->postcode);
            if ($this->service->lng()) {
                $dealership->update([
                    'coordinates' => $this->service->lat() . ',' . $this->service->lng(),
                    'lat' => $this->service->lat(),
                    'lng' => $this->service->lng(),
                ]);
            }
        } catch (\Exception $exception) {
            $this->output->error($exception->getMessage());
        }
    }
}
