<?php

namespace App\Domain\Training\Listeners;

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

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

    public function handle(EnrollmentCompleted $event): void
    {
        try {
            $participant = $event->enrollment->participant;

            $this->notificationService->sendSimple(
                type: 'enrollment_completed',
                recipientId: $participant->id,
                recipientType: 'participant',
                data: [
                    'participant_name' => $participant->person?->full_name ?? '',
                    'program_name' => $event->enrollment->trainingGroup?->trainingProgram?->name_ar ?? '',
                    'completion_date' => now()->format('Y-m-d'),
                ],
            );
        } catch (\Throwable $e) {
            Log::error('SendEnrollmentCompletedNotification failed: ' . $e->getMessage(), [
                'enrollment_id' => $event->enrollment->id,
            ]);
        }
    }

    public function failed(EnrollmentCompleted $event, \Throwable $exception): void
    {
        Log::critical('SendEnrollmentCompletedNotification PERMANENTLY FAILED', [
            'enrollment_id' => $event->enrollment->id,
            'error' => $exception->getMessage(),
        ]);
    }
}
