<?php

// Create this file: app/Providers/ScoutObserverServiceProvider.php

namespace App\Providers;

use App\Models\Bank;
use App\Models\Organization;
use App\Models\Post;
use App\Models\PostTranslation;
use App\Models\User;
use App\Observers\ScoutReindexObserver;
use Elastic\Elasticsearch\ClientBuilder;
use Illuminate\Support\ServiceProvider;

class ScoutObserverServiceProvider extends ServiceProvider
{
    /**
     * Register observers for Scout models
     */
    public function boot()
    {
        // Create a single observer instance to share across models
        $scoutObserver = new ScoutReindexObserver();

        // Register observer for User model
        User::observe($scoutObserver);

        // Register observer for Organization model
        Organization::observe($scoutObserver);

        // Register observer for Bank model
        Bank::observe($scoutObserver);

        // Register observer for Post model
        Post::observe($scoutObserver);

        // TODO NEXT: why not re-indexing with frsh data?

        // Add PostTranslation observer with custom logic
        PostTranslation::saved(function (PostTranslation $translation) {
            if ($translation->post_id) {
                $post = Post::find($translation->post_id);

                \Log::info('Before searchable:', [
                    'post_id' => $post->id,
                    'translations_loaded' => $post->relationLoaded('translations'),
                    'translation_count' => $post->translations->count(),
                    'searchable_array' => $post->toSearchableArray()
                ]);

                $post->searchable();

                // Wait a moment for Elasticsearch
                sleep(1);

                // Correct way to get Elasticsearch client for Matchish package
                $hosts = config('elastic.client.default.hosts', ['localhost:9200']);

                // Ensure hosts is always an array
                if (!is_array($hosts)) {
                    $hosts = [$hosts];
                }

                $client = ClientBuilder::create()
                    ->setHosts($hosts)
                    ->build();

                try {
                    $exists = $client->exists([
                        'index' => $post->searchableAs(),
                        'id' => $post->getScoutKey()
                    ]);

                    $indexedData = null;
                    if ($exists) {
                        $response = $client->get([
                            'index' => $post->searchableAs(),
                            'id' => $post->getScoutKey()
                        ]);
                        $indexedData = $response['_source'] ?? null;
                    }

                    \Log::info('After searchable:', [
                        'exists_in_index' => $exists,
                        'index_name' => $post->searchableAs(),
                        'scout_key' => $post->getScoutKey(),
                        'indexed_till_en' => $indexedData['post_translations']['till_en'] ?? 'not found'
                    ]);
                } catch (\Exception $e) {
                    \Log::error('Elasticsearch check failed', [
                        'error' => $e->getMessage()
                    ]);
                }
            }
        });


        PostTranslation::deleted(function (PostTranslation $translation) {
            if ($translation->post) {
                $translation->post->unsetRelation('translations');
                $translation->post->searchable();
            }
        });
    }
}
