<?php

namespace App\Domain\Participant\Listeners;

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

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

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

            if (!$guardian) {
                return;
            }

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

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