<?php

namespace App\Domain\Financial\Listeners;

use App\Domain\Financial\Events\InvoiceSent;
use App\Domain\Notification\Services\NotificationService;
use App\Domain\Shared\Helpers\PublicLinkHelper;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

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

    public function handle(InvoiceSent $event): void
    {
        try {
            $this->notificationService->sendSimple(
                type: 'invoice_sent',
                recipientId: $event->invoice->billable_id,
                recipientType: $event->invoice->billable_type,
                data: [
                    'participant_name' => $event->invoice->billable?->person?->full_name ?? '',
                    'invoice_number' => $event->invoice->number,
                    'total_amount' => number_format($event->invoice->total_amount / 100, 2),
                    'due_date' => $event->invoice->due_date?->format('Y-m-d'),
                    'public_link' => PublicLinkHelper::invoiceLink($event->invoice),
                ],
            );
        } catch (\Throwable $e) {
            Log::error('SendInvoiceSentNotification failed: ' . $e->getMessage(), [
                'invoice_id' => $event->invoice->id,
            ]);
        }
    }

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