<?php

namespace App\Console\Commands;

use App\Models\Announcement;
use App\Models\BlogPost;
use App\Models\KbArticle;
use App\Services\Search\AnnouncementSearchIndexer;
use App\Services\Search\BlogSearchIndexer;
use App\Services\Search\KnowledgebaseSearchIndexer;
use Illuminate\Console\Command;

class PostsReindex extends Command
{
    protected $signature = 'posts:reindex {--type=all : announcement|kb_article|blog_post|all}';

    protected $description = 'Rebuild Meilisearch indices for posts (per-type, per-locale).';

    public function handle(): int
    {
        $type = $this->option('type');

        $jobs = [
            'announcement' => [Announcement::class, AnnouncementSearchIndexer::class],
            'kb_article'   => [KbArticle::class, KnowledgebaseSearchIndexer::class],
            'blog_post'    => [BlogPost::class, BlogSearchIndexer::class],
        ];

        $targets = $type === 'all' ? array_keys($jobs) : [$type];

        foreach ($targets as $target) {
            if (! isset($jobs[$target])) {
                $this->error("Unknown type: {$target}");
                return self::FAILURE;
            }

            [$modelClass, $indexerClass] = $jobs[$target];
            $indexer = app($indexerClass);
            $indexer->ensureIndexConfigured();

            $count = 0;
            $modelClass::with('tags')->chunk(100, function ($posts) use ($indexer, &$count) {
                foreach ($posts as $post) {
                    $indexer->reindex($post);
                    $count++;
                }
            });

            $this->info("[{$target}] reindexed {$count} posts.");
        }

        return self::SUCCESS;
    }
}
