<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class FixBlogContentSeeder extends Seeder
{
    public function run(): void
    {
        $posts = DB::table('blog_posts')->whereNull('deleted_at')->get();
        $fixed = 0;

        foreach ($posts as $post) {
            $content = $post->content;

            if (!is_string($content)) {
                continue;
            }

            $trimmed = trim($content);

            if (str_starts_with($trimmed, '{')) {
                // JSON format: {"type":"html","html":"..."}
                $decoded = json_decode($trimmed, true);

                if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                    $html = $decoded['html'] ?? '';

                    if (is_array($html)) {
                        // Quill ops format
                        $html = collect($html)->map(fn($op) => $op['insert'] ?? '')->implode('');
                    }

                    DB::table('blog_posts')
                        ->where('id', $post->id)
                        ->update(['content' => $html]);

                    $fixed++;
                    $this->command->info("  Fixed post #{$post->id}: {$post->title}");
                }
            }
        }

        $this->command->info("✅ {$fixed} blog post(s) content fixed (JSON → plain HTML).");
    }
}
