<?php

namespace App\Observers;

use App\Facades\Settings;
use App\Jobs\AddDealerIdsToAutoTraderHub;
use Illuminate\Support\Facades\Log;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\Services\LocatingService;

class DealershipObserver
{
    private const AT_LOCATION_KEY = 'auto-trader-location-id';

    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) {
                Log::debug('Postcode coords not found: ' . $dealership->postcode);
                // skip
            }
        }
    }

    public function saved(Dealership $dealership): void
    {
        $newId = $dealership->data[self::AT_LOCATION_KEY] ?? null;
        $originalData = $dealership->getOriginal('data');
        $originalId = is_array($originalData) ? ($originalData[self::AT_LOCATION_KEY] ?? null) : null;

        if (empty($newId) || $newId === $originalId) {
            return;
        }

        if (!Settings::get('auto-trader-hub-enabled') || !Settings::get('auto-trader-hub-token')) {
            return;
        }

        AddDealerIdsToAutoTraderHub::dispatch([$newId]);
    }

    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');
    }
}
