<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('username', 50)->nullable()->unique()->after('name');
        });

        // Back-fill existing users with a unique slug
        DB::table('users')->orderBy('id')->each(function ($user) {
            $base = substr(Str::slug(trim($user->name)), 0, 18);
            if ($base === '') $base = 'user';
            do {
                $slug = $base . '-' . Str::lower(Str::random(6));
            } while (DB::table('users')->where('username', $slug)->exists());
            DB::table('users')->where('id', $user->id)->update(['username' => $slug]);
        });
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('username');
        });
    }
};
