<?php

namespace App\Domain\Financial\Listeners;

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

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

    public function handle(InvoiceOverdue $event): void
    {
        try {
            $this->notificationService->sendSimple(
                type: 'invoice_overdue',
                recipientId: $event->invoice->billable_id,
                recipientType: $event->invoice->billable_type,
                data: [
                    'invoice_number' => $event->invoice->number,
                    'total_amount' => $event->invoice->total_amount,
                    'balance_due' => $event->invoice->due_amount,
                    'due_date' => $event->invoice->due_date?->format('Y-m-d'),
                    'days_overdue' => $event->invoice->due_date?->diffInDays(now()),
                ],
            );
        } catch (\Throwable $e) {
            Log::error('SendOverdueReminder failed: ' . $e->getMessage(), [
                'invoice_id' => $event->invoice->id,
            ]);
        }
    }

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