<?php

namespace App\Console\Commands;

use App\Helpers\MigrationHelpers;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use League\HTMLToMarkdown\HtmlConverter;

#[Signature('fix:entries-description')]
#[Description('Reconvert HTML descriptions to Markdown')]
class FixEntriesDescription extends Command
{
    public function handle()
    {
        $converter = new HtmlConverter(['hard_break' => true]);

        $rows = DB::table('migrations_logs')
            ->where('source_system', 'wp')
            ->where('source_table', 'wp_posts')
            ->where('target_table', 'entries')
            ->get(['source_id', 'target_id']);

        $this->info("{$rows->count()} entries touched.");

        $this->withProgressBar($rows, function ($row) use ($converter) {
            $rawHtml = DB::connection('old_wp')->table('posts')
                ->where('ID', $row->source_id)
                ->value('post_content');

            if ($rawHtml === null) return;

            $markdown = trim($rawHtml) === '' ? $rawHtml : $converter->convert(MigrationHelpers::wpAutoP($rawHtml));

            DB::table('entries')->where('id', $row->target_id)->update([
                'description' => $markdown,
                'updated_at' => now(),
            ]);
        });

        $this->newLine();
        $this->info('Process finished.');
        return self::SUCCESS;
    }
}
