<?php

namespace App\Domain\Financial\Listeners;

use App\Domain\Financial\Events\InvoiceOverdue;
use App\Domain\Notification\Services\NotificationService;
use App\Domain\Shared\Helpers\PublicLinkHelper;
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: [
                    'participant_name' => $event->invoice->billable?->person?->full_name ?? '',
                    'invoice_number' => $event->invoice->number,
                    'total_amount' => number_format($event->invoice->total_amount / 100, 2),
                    'balance_due' => number_format($event->invoice->due_amount / 100, 2),
                    'due_date' => $event->invoice->due_date?->format('Y-m-d'),
                    'days_overdue' => (string) ($event->invoice->due_date?->diffInDays(now()) ?? 0),
                    'public_link' => PublicLinkHelper::invoiceLink($event->invoice),
                ],
            );
        } 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(),
        ]);
    }
}
