<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\ForumPost;
use App\Services\BbcodeConverter;

class ForumConvertPosts extends Command
{
    protected $signature = 'forum:convert-posts {--dry-run} {--chunk=500} {--limit=} {--report}';

    protected $description = 'Convert migrated forum posts content from legacy BBCode to HTML in-place';

    public function handle(): int
    {
        $dry = $this->option('dry-run');
        $chunk = (int)$this->option('chunk');
        $limit = $this->option('limit') ? (int)$this->option('limit') : null;

        $query = ForumPost::query()->orderBy('id');
        $total = $limit ? min($query->count(), $limit) : $query->count();

        $this->info('Converting forum posts (dry-run='.($dry ? 'yes' : 'no').')');
        $this->info("Total posts to consider: {$total}");

        $bar = $this->output->createProgressBar($total);
        $bar->start();

        $converter = new BbcodeConverter();
        $processed = 0;
        $changed = 0;

        try {
            $query->chunkById($chunk, function ($posts) use (&$bar, &$processed, &$changed, $dry, $limit, $converter) {
                foreach ($posts as $post) {
                    if ($limit !== null && $processed >= $limit) {
                        throw new \RuntimeException('limit_reached');
                    }
                    $bar->advance();
                    $processed++;

                    $old = $post->content ?? '';
                    $new = $converter->convert($old);

                    if ($old === $new) {
                        continue;
                    }

                    $changed++;
                    if ($dry) {
                        $this->line('[dry] would update post ' . $post->id);
                        continue;
                    }

                    $post->content = $new;
                    $post->save();
                }
            });
        } catch (\RuntimeException $e) {
            if ($e->getMessage() !== 'limit_reached') {
                throw $e;
            }
            // intentionally stop chunking when limit reached
        }

        $bar->finish();
        $this->line('');

        $this->info("Processed: {$processed} posts. Changed: {$changed} posts.");

        if ($this->option('report')) {
            $this->info('Conversion complete');
        }

        return 0;
    }
}
