<?php

namespace App\Observers;

use Illuminate\Support\Facades\Log;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\Services\LocatingService;

class DealershipObserver
{
    public function __construct(private readonly LocatingService $locatingService)
    {
    }

    public function updating(Dealership $dealership)
    {
        if ($this->shouldPerformCoordinateLookup($dealership)) {
            try {
                $dealership->coordinates = $this->locatingService->locate($dealership->postcode)->asString();
            } catch (\Exception $exception) {
                Log::debug('Postcode coords not found: ' . $dealership->postcode);
                // skip
            }
        }
    }

    private function shouldPerformCoordinateLookup(Dealership $dealership): bool
    {
        $clearedCoordsWithSamePostcode = $dealership->isDirty('postcode')
            && empty($dealership->coordinates)
            && !$dealership->isDirty('postcode');

        if (!empty($dealership->coordinates) || $clearedCoordsWithSamePostcode || empty($dealership->postcode)) {
            return false;
        }

        return $dealership->isDirty('postcode');
    }
}
