<?php

namespace App\Domain\Financial\Listeners;

use App\Domain\Financial\Events\PaymentReceived;
use App\Domain\Financial\Models\CashSession;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class UpdateCashSessionTotals implements ShouldQueue
{
    public function handle(PaymentReceived $event): void
    {
        try {
            $payment = $event->payment;

            if ($payment->method !== \App\Domain\Financial\Enums\PaymentMethod::Cash) {
                return;
            }

            $cashSession = CashSession::where('user_id', $event->actor->id)
                ->where('status', 'open')
                ->first();

            if (!$cashSession) {
                return;
            }

            $cashSession->increment('transactions_count');
            $cashSession->increment('total_cash_in', $payment->amount);
        } catch (\Throwable $e) {
            Log::error('UpdateCashSessionTotals failed: ' . $e->getMessage(), [
                'payment_id' => $event->payment->id,
            ]);
        }
    }

    public function failed(PaymentReceived $event, \Throwable $exception): void
    {
        Log::critical('UpdateCashSessionTotals PERMANENTLY FAILED', [
            'payment_id' => $event->payment->id,
            'error' => $exception->getMessage(),
        ]);
    }
}
