<?php

namespace App\Domain\Financial\Listeners;

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

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

    public function handle(PaymentPlanDefaulted $event): void
    {
        try {
            $invoice = $event->paymentPlan->invoice;

            $this->notificationService->sendSimple(
                type: 'payment_plan_defaulted',
                recipientId: $invoice->billable_id,
                recipientType: $invoice->billable_type,
                data: [
                    'participant_name' => $invoice->billable?->person?->full_name ?? '',
                    'plan_id' => (string) $event->paymentPlan->id,
                    'overdue_amount' => number_format(($event->paymentPlan->installments()->where('status', 'overdue')->sum('amount') ?? 0) / 100, 2),
                    'installment_date' => $event->paymentPlan->installments()->where('status', 'overdue')->first()?->due_date?->format('Y-m-d') ?? '',
                ],
                priority: 'high',
            );
        } catch (\Throwable $e) {
            Log::error('SendPaymentPlanDefaultedNotification failed: ' . $e->getMessage(), [
                'payment_plan_id' => $event->paymentPlan->id,
            ]);
        }
    }

    public function failed(PaymentPlanDefaulted $event, \Throwable $exception): void
    {
        Log::critical('SendPaymentPlanDefaultedNotification PERMANENTLY FAILED', [
            'payment_plan_id' => $event->paymentPlan->id,
            'error' => $exception->getMessage(),
        ]);
    }
}
