<?php

namespace App\Domain\Training\Listeners;

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

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

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

            if (!$guardian) {
                return;
            }

            $this->notificationService->sendSimple(
                type: 'participant_status_changed',
                recipientId: $guardian->id,
                recipientType: 'guardian',
                data: [
                    'participant_name' => $event->participant->person?->full_name ?? '',
                    'old_status' => $event->oldStatus,
                    'new_status' => $event->newStatus,
                    'reason' => $event->participant->status_reason ?? '',
                ],
            );
        } catch (\Throwable $e) {
            Log::error('SendParticipantStatusChangedNotification failed: ' . $e->getMessage(), [
                'participant_id' => $event->participant->id,
            ]);
        }
    }

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