<?php

namespace App\Observers;

use App\Facades\Settings;
use Mtc\MercuryDataModels\VehicleAttribute;

class VehicleAttributeObserver
{
    public function updating(VehicleAttribute $vehicleAttribute): void
    {
        if ($vehicleAttribute->isDirty('sortable')) {
            $this->handleSortableChange($vehicleAttribute);
        }

        if ($vehicleAttribute->isDirty('filterable')) {
            $this->handleFilterableChange($vehicleAttribute);
        }
    }

    protected function handleSortableChange(VehicleAttribute $vehicleAttribute): void
    {
        $configKey = 'automotive-vehicle-sorting-' . $vehicleAttribute->slug;

        if ($vehicleAttribute->sortable) {
            if (!Settings::exists($configKey)) {
                Settings::make([
                    'tab' => 'Automotive',
                    'section' => 'Filter',
                    'group' => 'Sorting',
                    'name' => $vehicleAttribute->name,
                    'config_key' => $configKey,
                    'type' => 'boolean',
                    'value' => true,
                ]);
            }
        } else {
            Settings::delete($configKey);
        }
    }

    protected function handleFilterableChange(VehicleAttribute $vehicleAttribute)
    {
        $configKey = 'automotive-vehicle-filters-' . $vehicleAttribute->slug;

        if ($vehicleAttribute->filterable) {
            if (!Settings::exists($configKey)) {
                Settings::make([
                    'tab' => 'Automotive',
                    'section' => 'Filter',
                    'group' => 'Filtering',
                    'name' => $vehicleAttribute->name,
                    'config_key' => $configKey,
                    'type' => 'boolean',
                    'value' => true,
                ]);
            }
        } else {
            Settings::delete($configKey);
        }
    }
}
