<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('surveys', function (Blueprint $table) {
            $table->uuid('uuid')->after('id')->nullable();
        });

        // Backfill existing records
        \Illuminate\Support\Facades\DB::table('surveys')->get()->each(function ($survey) {
            \Illuminate\Support\Facades\DB::table('surveys')
                ->where('id', $survey->id)
                ->update(['uuid' => (string) \Illuminate\Support\Str::uuid()]);
        });

        // Make it non-nullable (optional, but good practice if driver supports it easily)
        // For portability/safety without doctrine, we might just leave it nullable but enforce in app.
        // Or if we are sure, we can try change(). Let's stick to nullable for now to avoid dependency issues,
        // but creating it unique is important.
        
        Schema::table('surveys', function (Blueprint $table) {
             // Adding unique index after population
             $table->unique('uuid');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('surveys', function (Blueprint $table) {
            $table->dropColumn('uuid');
        });
    }
};
