<?php

namespace App\Domain\Financial\Listeners;

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

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

    public function handle(InvoiceCreated $event): void
    {
        try {
            $this->notificationService->sendSimple(
                type: 'invoice_created',
                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('SendInvoiceNotification failed: ' . $e->getMessage(), [
                'invoice_id' => $event->invoice->id,
            ]);
        }
    }

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