<?php

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

return new class extends Migration
{
    /**
     * Cada usuario obtiene su propio código de referido para compartir
     * (antes solo existía para revendedores aprobados vía reseller_code).
     */
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('referral_code')->nullable()->unique()->after('referred_by_id');
        });

        // Backfill de usuarios existentes con un código generado
        DB::table('users')->select('id', 'name')->orderBy('id')->get()->each(function ($user) {
            $base = Str::upper(Str::slug(explode(' ', trim($user->name))[0] ?: 'USER', ''));
            $base = $base !== '' ? $base : 'USER';

            do {
                $code = $base . '-' . Str::upper(Str::random(2));
            } while (DB::table('users')->where('referral_code', $code)->exists());

            DB::table('users')->where('id', $user->id)->update(['referral_code' => $code]);
        });
    }

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