<?php

namespace App\Domain\Financial\Listeners;

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

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

    public function handle(InstallmentOverdue $event): void
    {
        try {
            $plan = $event->installment->paymentPlan;
            $this->notificationService->sendSimple(
                type: 'installment_overdue',
                recipientId: $plan->participant_id,
                recipientType: 'participant',
                data: [
                    'installment_sequence' => $event->installment->sequence,
                    'amount' => $event->installment->amount,
                    'due_date' => $event->installment->due_date->format('Y-m-d'),
                ],
            );
        } catch (\Throwable $e) {
            Log::error('NotifyInstallmentDue failed: ' . $e->getMessage(), [
                'installment_id' => $event->installment->id,
            ]);
        }
    }

    public function failed(InstallmentOverdue $event, \Throwable $exception): void
    {
        Log::critical('NotifyInstallmentDue PERMANENTLY FAILED', [
            'installment_id' => $event->installment->id,
            'error' => $exception->getMessage(),
        ]);
    }
}
