<?php

namespace App\Domain\Notification\Listeners;

use App\Domain\Financial\Events\InstallmentOverdue;
use App\Domain\Notification\Services\PushNotificationService;
use App\Domain\Participant\Models\Participant;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendInstallmentOverduePush implements ShouldQueue
{
    public function __construct(private PushNotificationService $pushService) {}

    public function handle(InstallmentOverdue $event): void
    {
        $installment = $event->installment;
        $invoice = $installment->paymentPlan?->invoice;

        if (!$invoice) {
            return;
        }

        if ($invoice->billable_type !== 'App\\Domain\\Participant\\Models\\Participant') {
            return;
        }

        $participant = Participant::find($invoice->billable_id);
        if (!$participant) {
            return;
        }

        $amount = number_format($installment->amount / 100, 2);

        $this->pushService->sendToParticipantGuardians(
            $participant,
            'قسط متأخر',
            "قسط بقيمة {$amount} ج.م تجاوز تاريخ الاستحقاق",
            [
                'type' => 'installment_overdue',
                'route' => '/participants/{participant_uuid}/installments',
                'participant_uuid' => $participant->uuid,
                'invoice_uuid' => $invoice->uuid,
                'amount' => $installment->amount,
            ],
            'installment.overdue'
        );
    }
}
