<?php
namespace App\Services;

use App\Models\User;
use App\Models\Transaction;
use Illuminate\Support\Facades\Log;

class ReferralService
{
    protected float $referrerBonus = 10.00;
    protected float $newUserBonus = 5.00;

    public function applyReferralBonus(User $newUser, string $currency): bool
    {
        $referrer = $newUser->referrer;

        if (!$referrer || $referrer->id === $newUser->id) {
            Log::warning('Referral skipped: invalid referrer', [
                'new_user_id' => $newUser->id,
            ]);
            return false;
        }

        $referrer->load('profile.accounts');
        $newUser->load('profile.accounts');

        $referrerAccount = $referrer->profile?->accounts->first();
        $newUserAccount = $newUser->profile?->accounts->first();


        if (!$referrerAccount || !$newUserAccount) {
            Log::warning('Referral skipped: accounts missing', [
                'referrer_id' => $referrer->id,
                'new_user_id' => $newUser->id,
            ]);
            return false;
        }

        // Prevent double bonus
        $alreadyGiven = Transaction::where('type', 'referral_bonus')
            ->where('account_id', $referrerAccount->id)
            ->where('referral_user_id', $newUser->id)
            ->exists();

        if ($alreadyGiven) {
            Log::info('Referral bonus already applied', [
                'new_user_id' => $newUser->id,
            ]);
            return false;
        }

        // Apply bonuses
        $referrerAccount->increment('balance', $this->referrerBonus);
        $newUserAccount->increment('balance', $this->newUserBonus);

        $referrerAccount->refresh();
        $newUserAccount->refresh();

        Transaction::create([
            'account_id' => $referrerAccount->id,
            'type' => 'referral_bonus',
            'amount' => $this->referrerBonus,
            'status' => 'approved',
            'currency' => $currency,
            'description' => 'Referral bonus for referring user ID ' . $newUser->id,
            'balance_after' => $referrerAccount->balance,
            'referral_user_id' => $newUser->id,
        ]);

        Transaction::create([
            'account_id' => $newUserAccount->id,
            'type' => 'signup_bonus',
            'amount' => $this->newUserBonus,
            'status' => 'approved',
            'currency' => $currency,
            'description' => 'Signup bonus from referral',
            'balance_after' => $newUserAccount->balance,
        ]);

        Log::info('Referral bonuses applied successfully', [
            'referrer_id' => $referrer->id,
            'new_user_id' => $newUser->id,
            'referrer_balance' => $referrerAccount->balance,
            'new_user_balance' => $newUserAccount->balance,
        ]);

        return true;
    }
}
