<?php

namespace App\Domain\Training\Listeners;

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

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

    public function handle(WaitlistSpotAvailable $event): void
    {
        try {
            $this->notificationService->sendSimple(
                type: 'waitlist_spot_available',
                recipientId: $event->waitlist->participant_id,
                recipientType: 'participant',
                data: [
                    'group_name' => $event->group->name_ar,
                    'position' => $event->waitlist->position,
                ],
            );
        } catch (\Throwable $e) {
            Log::error('NotifyWaitlistSpot failed: ' . $e->getMessage(), [
                'waitlist_id' => $event->waitlist->id,
            ]);
        }
    }

    public function failed(WaitlistSpotAvailable $event, \Throwable $exception): void
    {
        Log::critical('NotifyWaitlistSpot PERMANENTLY FAILED', [
            'waitlist_id' => $event->waitlist->id,
            'error' => $exception->getMessage(),
        ]);
    }
}
