<?php

namespace App\Observers;

use App\Models\MaintenanceRecord;
use App\Models\Vehicle;

class MaintenanceRecordObserver
{
    /**
     * Handle the MaintenanceRecord "created" event.
     */
    public function created(MaintenanceRecord $maintenanceRecord): void
    {
        $this->updateVehicleOdometer($maintenanceRecord);
    }

    /**
     * Handle the MaintenanceRecord "updated" event.
     */
    public function updated(MaintenanceRecord $maintenanceRecord): void
    {
        $this->updateVehicleOdometer($maintenanceRecord);
    }

    /**
     * Update the vehicle's current odometer if the new reading is higher.
     */
    private function updateVehicleOdometer(MaintenanceRecord $maintenanceRecord): void
    {
        // Ensure there's an odometer reading and a related vehicle.
        if ($maintenanceRecord->odometer_reading && $maintenanceRecord->vehicle) {
            $vehicle = $maintenanceRecord->vehicle;

            // Update the vehicle's odometer only if the new reading is greater.
            if ($maintenanceRecord->odometer_reading > $vehicle->current_odometer) {
                $vehicle->current_odometer = $maintenanceRecord->odometer_reading;
                $vehicle->save();
            }
        }
    }

    /**
     * Handle the MaintenanceRecord "deleted" event.
     */
    public function deleted(MaintenanceRecord $maintenanceRecord): void
    {
        //
    }

    /**
     * Handle the MaintenanceRecord "restored" event.
     */
    public function restored(MaintenanceRecord $maintenanceRecord): void
    {
        //
    }

    /**
     * Handle the MaintenanceRecord "force deleted" event.
     */
    public function forceDeleted(MaintenanceRecord $maintenanceRecord): void
    {
        //
    }
}
