<?php

namespace App\Listeners;

use App\Events\OrderApproved;
use App\Models\Order;
use App\Services\BinaryLedgerService;

class HandleOrderApproved
{
    public function __construct(private readonly BinaryLedgerService $binaryLedgerService)
    {
    }

    public function handle(OrderApproved $event): void
    {
        $order = Order::query()->find($event->orderId);
        if (! $order || $order->status !== 'approved' || ! $order->user_id) {
            return;
        }

        $user = $order->user;
        if (! $user) {
            return;
        }

        $this->binaryLedgerService->postRepurchaseUpline(
            $user,
            (float) $event->totalBv,
            'order_approved',
            $event->orderId
        );
    }
}
