<?php

namespace Artemis\Loyalty\Console\Commands;

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

class GenerateReferralCodes  extends Command
{
    protected $signature = 'loyalty:generate-referral';
    protected $description = 'Generate referral codes for users who don\'t have one';

    public function handle()
    {
        $users = User::whereNull('referral_code')->get();

        $this->info("Generating referral codes for {$users->count()} users...");

        $users->each(function ($user) {
            $user->update([
                'referral_code' => $this->generateUniqueReferralCode()
            ]);
        });

        $this->info('Referral codes generated successfully!');
    }

    protected function generateUniqueReferralCode()
    {
        do {
            $code = Str::upper(Str::random(8));
        } while (User::where('referral_code', $code)->exists());

        return $code;
    }
}
