<?php

namespace App\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Str;

class GenerateReferralCodes extends Command
{
    protected $signature = 'referral:generate-codes {--dry-run : Show what would be updated without making changes}';
    protected $description = 'Generate referral codes for users who do not have one';

    public function handle(): int
    {
        $dryRun = $this->option('dry-run');
        
        $users = User::where(function ($q) {
            $q->whereNull('referral_code')
              ->orWhere('referral_code', '');
        })->get();
        
        if ($users->isEmpty()) {
            $this->info('✅ All users already have referral codes.');
            return self::SUCCESS;
        }
        
        $this->info(sprintf('Found %d users without referral codes.', $users->count()));
        
        if ($dryRun) {
            $this->info('DRY RUN - No changes will be made.');
            foreach ($users as $user) {
                $this->line(sprintf('  - %s (%s)', $user->name, $user->email));
            }
            return self::SUCCESS;
        }
        
        $bar = $this->output->createProgressBar($users->count());
        $bar->start();
        
        foreach ($users as $user) {
            do {
                $code = strtoupper(Str::random(8));
            } while (User::where('referral_code', $code)->exists());
            
            $user->update(['referral_code' => $code]);
            $bar->advance();
        }
        
        $bar->finish();
        $this->newLine();
        $this->info('✅ Referral codes generated successfully!');
        
        return self::SUCCESS;
    }
}
