<?php

namespace App\Console\Commands;

use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

#[Signature('fix:encoded-slugs')]
class FixEncodedSlugs extends Command
{
    private const array TABLES = [
        'entries', 'games', 'platforms', 'genres', 'languages', 'modifications',
        'levels', 'statuses', 'authors', 'categories', 'systems',
    ];

    public function handle()
    {
        foreach (self::TABLES as $table) {
            $rows = DB::table($table)->where('slug', 'like', '%\\%%')->get(['id', 'slug']);
            $fixed = 0;

            foreach ($rows as $row) {
                $decoded = rawurldecode($row->slug);
                if ($decoded === $row->slug) continue;

                try {
                    DB::table($table)->where('id', $row->id)->update(['slug' => $decoded]);
                    $fixed++;
                } catch (\Throwable $e) {
                    $this->warn("{$table}#{$row->id} : collision '{$decoded}', ignored ({$e->getMessage()}).");
                }
            }

            if ($fixed > 0) {
                $this->info("{$table}: {$fixed} fixed slugs.");
            }
        }
    }
}
