<?php

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

return new class extends Migration
{
    public function up(): void
    {
        $usedNumbers = DB::table('customers')
            ->whereNotNull('account_number')
            ->pluck('account_number')
            ->filter(fn ($number): bool => preg_match('/^\d{10}$/', (string) $number) === 1)
            ->flip();

        DB::table('customers')
            ->select(['id', 'account_number'])
            ->orderBy('id')
            ->chunkById(100, function ($customers) use (&$usedNumbers): void {
                foreach ($customers as $customer) {
                    if (preg_match('/^\d{10}$/', (string) $customer->account_number) === 1) {
                        continue;
                    }

                    do {
                        $accountNumber = (string) random_int(1000000000, 9999999999);
                    } while ($usedNumbers->has($accountNumber));

                    DB::table('customers')
                        ->where('id', $customer->id)
                        ->update([
                            'account_number' => $accountNumber,
                            'updated_at' => now(),
                        ]);

                    $usedNumbers->put($accountNumber, true);
                }
            });
    }

    public function down(): void
    {
        // Customer account numbers are active business identifiers and are not reverted.
    }
};
