<?php

namespace App\Domain\Financial\Listeners;

use App\Domain\Financial\Events\InvoiceCreated;
use App\Domain\Notification\Services\NotificationService;
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: [
                    'invoice_number' => $event->invoice->number,
                    'total_amount' => $event->invoice->total_amount,
                    'due_date' => $event->invoice->due_date?->format('Y-m-d'),
                ],
            );
        } 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(),
        ]);
    }
}
