<?php

namespace App\Listeners\Search;

use App\Events\TranslationUpdated;
use App\Models\Announcement;
use App\Models\BlogPost;
use App\Models\KbArticle;

class ReindexOnTranslationUpdate
{
    /**
     * Route TranslationUpdated events for Post subclasses to the matching
     * search indexer. Indexer sınıfları Phase 5'te yaratılacak; o zamana
     * kadar `class_exists` + try/catch guard'ları ile translation save'leri
     * patlatmadan silent skip yapıyoruz.
     */
    public function handle(TranslationUpdated $event): void
    {
        $model = $event->model;

        $indexerClass = match (true) {
            $model instanceof Announcement => 'App\Services\Search\AnnouncementSearchIndexer',
            $model instanceof KbArticle    => 'App\Services\Search\KnowledgebaseSearchIndexer',
            $model instanceof BlogPost     => 'App\Services\Search\BlogSearchIndexer',
            default                        => null,
        };

        if ($indexerClass === null || ! class_exists($indexerClass)) {
            return; // Phase 5 indexer'lar gelene kadar silent skip
        }

        try {
            app($indexerClass)->reindex($model);
        } catch (\Throwable) {
            // Translation save'i patlatma — search indexer hatası fatal değil.
        }
    }
}
