<?php

namespace App\Domain\Participant\Listeners;

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

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

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

            if (!$guardian) {
                return;
            }

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

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