<?php

namespace App\Listeners;

use App\Models\Affiliate;
use App\Models\AffiliateReferral;
use App\Models\CreditTransaction;
use Illuminate\Auth\Events\Registered;

class GiveBonusCredits
{
    public function handle(Registered $event): void
    {
        $user = $event->user;
        $role = $user->role?->value ?? 'user';

        // Keine Onboarding-Credits für interne Rollen
        $skipCredits = in_array($role, [
            'admin',
            'super_admin',
            'developer',
            'support',
        ]);

        if (!$skipCredits) {
            CreditTransaction::onboarding($user, 300);
        }

        // Kein Affiliate-Account für interne Rollen
        $skipAffiliate = in_array($role, [
            'admin',
            'super_admin',
            'developer',
            'support',
        ]);

        if (!$skipAffiliate) {
            Affiliate::create([
                'user_id' => $user->id,
                'code'    => Affiliate::generateCode($user),
                'status'  => 'active',
            ]);
        }

        // Referral tracken — nur für nicht-interne User
        if (!$skipCredits) {
            $refCode = session()->pull('affiliate_ref_code');
            if ($refCode) {
                $affiliate = Affiliate::where('code', $refCode)
                    ->where('status', 'active')
                    ->first();

                if ($affiliate && $affiliate->user_id !== $user->id) {
                    AffiliateReferral::create([
                        'affiliate_id'     => $affiliate->id,
                        'referred_user_id' => $user->id,
                        'affiliate_code'   => $refCode,
                        'status'           => 'pending',
                        'registered_at'    => now(),
                        'qualifies_at'     => now()->addMonths(3),
                    ]);

                    $affiliate->increment('total_referrals');
                }
            }
        }
    }
}
