<?php

namespace App\Domain\Financial\Listeners;

use App\Domain\Financial\Events\PaymentReceived;
use App\Domain\Notification\Services\NotificationService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class SendPaymentConfirmation implements ShouldQueue
{
    public function __construct(
        private NotificationService $notificationService,
    ) {}

    public function handle(PaymentReceived $event): void
    {
        try {
            $this->notificationService->sendSimple(
                type: 'payment_received',
                recipientId: $event->payment->payer_id,
                recipientType: $event->payment->payer_type,
                data: [
                    'payment_reference' => $event->payment->reference,
                    'amount' => $event->payment->amount,
                    'method' => $event->payment->method,
                    'invoice_number' => $event->payment->invoice?->number,
                ],
            );
        } catch (\Throwable $e) {
            Log::error('SendPaymentConfirmation failed: ' . $e->getMessage(), [
                'payment_id' => $event->payment->id,
            ]);
        }
    }

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