<?php

// Create this file: app/Observers/ScoutReindexObserver.php

namespace App\Observers;

use Illuminate\Support\Facades\Log;

class ScoutReindexObserver
{
    /**
     * Handle the model "created" event.
     */
    public function created($model)
    {
        $this->reindexModel($model, 'created');
    }

    /**
     * Handle the model "updated" event.
     */
    public function updated($model)
    {
        $this->reindexModel($model, 'updated');
    }

    /**
     * Handle the model "deleted" event.
     */
    public function deleted($model)
    {
        // For deleted models, remove from search index
        if (method_exists($model, 'unsearchable')) {
            $model->unsearchable();

            Log::info('Observer: Removed from search index', [
                'model' => get_class($model),
                'id' => $model->id,
                'event' => 'deleted'
            ]);
        }
    }

    /**
     * Handle the model "restored" event.
     */
    public function restored($model)
    {
        $this->reindexModel($model, 'restored');
    }

    /**
     * Reindex the model if it uses Scout
     */
    private function reindexModel($model, $event)
    {
        // Check if this model uses Scout
        if (method_exists($model, 'searchable') && method_exists($model, 'searchableAs')) {

            // Skip reindexing if only timestamp was updated (to avoid infinite loops)
            if ($event === 'updated' && $this->onlyTimestampsChanged($model)) {
                return;
            }

            try {
                $model->searchable();

                Log::info('Observer: Model reindexed', [
                    'model' => get_class($model),
                    'id' => $model->id,
                    'event' => $event
                ]);
            } catch (\Exception $e) {
                Log::error('Observer: Failed to reindex model', [
                    'model' => get_class($model),
                    'id' => $model->id,
                    'event' => $event,
                    'error' => $e->getMessage()
                ]);
            }
        }
    }

    /**
     * Check if only timestamps were changed (to avoid infinite reindexing loops)
     */
    private function onlyTimestampsChanged($model)
    {
        if (!$model->isDirty()) {
            return false;
        }

        $dirty = $model->getDirty();
        $timestampFields = ['updated_at', 'created_at'];

        // Remove timestamp fields from dirty array
        $nonTimestampChanges = array_diff_key($dirty, array_flip($timestampFields));

        // If only timestamps changed, return true
        return empty($nonTimestampChanges);
    }
}
