<?php

namespace App\Listeners;

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

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

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

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

        $this->binaryLedgerService->postReversal(
            $user,
            'repurchase',
            (float) $order->total_bv,
            'order_cancelled',
            $event->orderId
        );
    }
}
