<?php

namespace App\Domain\Training\Listeners;

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

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

    public function handle(ParticipantRegistered $event): void
    {
        try {
            $guardian = $event->participant->primaryGuardian;

            if (!$guardian) {
                return;
            }

            $this->notificationService->sendSimple(
                type: 'participant_registered',
                recipientId: $guardian->id,
                recipientType: 'guardian',
                data: [
                    'participant_name' => $event->participant->person?->full_name ?? '',
                    'registration_date' => $event->participant->registration_date?->format('Y-m-d') ?? now()->format('Y-m-d'),
                    'participant_number' => $event->participant->participant_number ?? '',
                ],
            );
        } catch (\Throwable $e) {
            Log::error('SendParticipantRegisteredNotification failed: ' . $e->getMessage(), [
                'participant_id' => $event->participant->id,
            ]);
        }
    }

    public function failed(ParticipantRegistered $event, \Throwable $exception): void
    {
        Log::critical('SendParticipantRegisteredNotification PERMANENTLY FAILED', [
            'participant_id' => $event->participant->id,
            'error' => $exception->getMessage(),
        ]);
    }
}
