<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('meetup_participants', function (Blueprint $table) {
            $table->string('user_id', 32)->nullable()->after('slug');
        });

        $alphabet = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
        $existing = [];

        foreach (DB::table('meetup_participants')->orderBy('id')->get() as $row) {
            do {
                $id = 'MXP-';
                for ($i = 0; $i < 8; $i++) {
                    $id .= $alphabet[random_int(0, strlen($alphabet) - 1)];
                }
            } while (isset($existing[$id]));

            $existing[$id] = true;
            DB::table('meetup_participants')->where('id', $row->id)->update(['user_id' => $id]);
        }

        Schema::table('meetup_participants', function (Blueprint $table) {
            $table->unique('user_id');
        });
    }

    public function down(): void
    {
        Schema::table('meetup_participants', function (Blueprint $table) {
            $table->dropUnique(['user_id']);
            $table->dropColumn('user_id');
        });
    }
};
