<?php

namespace App\Listeners;

use App\Events\OrderApprovedEvent;
use App\Models\Order;
use App\Services\CommissionEngine;
use Illuminate\Contracts\Queue\ShouldQueue;

class HandleOrderApprovedCommission implements ShouldQueue
{
    public function __construct(private readonly CommissionEngine $commissionEngine)
    {
    }

    public function handle(OrderApprovedEvent $event): void
    {
        $order = Order::query()->with('user.currentRank')->find($event->orderId);
        if (! $order || $order->status !== 'approved') {
            return;
        }

        $this->commissionEngine->calculateDirectReferralIncome($order);
        $this->commissionEngine->calculateBinaryIncome($order);
        $this->commissionEngine->calculateLevelIncome($order);
        $this->commissionEngine->calculateMatrixIncome($order);
        $this->commissionEngine->calculateUnilevelCommission($order);
        $this->commissionEngine->calculateGenerationBonus($order);
        $this->commissionEngine->calculateLeadershipBonus($order);
        $this->commissionEngine->calculateMatchingBonus($order);
        $this->commissionEngine->calculateRankBonus($order);
        $this->commissionEngine->calculateRoiIncome($order);
    }
}
