<?php

namespace App\Domain\Financial\Listeners;

use App\Domain\Financial\Events\PaymentReceived;
use App\Domain\Notification\Services\NotificationService;
use App\Domain\Shared\Helpers\PublicLinkHelper;
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: [
                    'participant_name' => $event->payment->invoice?->billable?->person?->full_name ?? '',
                    'payment_amount' => number_format($event->payment->amount / 100, 2),
                    'payment_method' => $event->payment->method?->value ?? $event->payment->method ?? '',
                    'invoice_number' => $event->payment->invoice?->number ?? '',
                    'receipt_link' => PublicLinkHelper::receiptLink($event->payment),
                ],
            );
        } 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(),
        ]);
    }
}
