<?php

namespace App\Observers;

use App\Models\User;
use Illuminate\Support\Facades\DB;

class UserObserver
{
    /**
     * Handle the User "creating" event.
     */
    public function creating(User $user): void
    {
        if (empty($user->codice_univoco)) {
            $user->codice_univoco = $this->generateCodiceUnivoco();
        }
    }

    /**
     * Genera un codice univoco di 8 caratteri alfanumerici
     */
    private function generateCodiceUnivoco(): string
    {
        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        
        do {
            $codice = '';
            for ($i = 0; $i < 8; $i++) {
                $codice .= $characters[random_int(0, 35)];
            }
            
            $exists = DB::table('users')->where('codice_univoco', $codice)->exists();
        } while ($exists);
        
        return $codice;
    }
}
