<?php

namespace App\Domain\Financial\Listeners;

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

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

    public function handle(InvoiceCancelled $event): void
    {
        try {
            $this->notificationService->sendSimple(
                type: 'invoice_cancelled',
                recipientId: $event->invoice->billable_id,
                recipientType: $event->invoice->billable_type,
                data: [
                    'participant_name' => $event->invoice->billable?->person?->full_name ?? '',
                    'invoice_number' => $event->invoice->number,
                    'reason' => $event->invoice->cancellation_reason ?? '',
                ],
            );
        } catch (\Throwable $e) {
            Log::error('SendInvoiceCancelledNotification failed: ' . $e->getMessage(), [
                'invoice_id' => $event->invoice->id,
            ]);
        }
    }

    public function failed(InvoiceCancelled $event, \Throwable $exception): void
    {
        Log::critical('SendInvoiceCancelledNotification PERMANENTLY FAILED', [
            'invoice_id' => $event->invoice->id,
            'error' => $exception->getMessage(),
        ]);
    }
}
