<?php

namespace App\Domain\Training\Listeners;

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

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

    public function handle(SessionCancelled $event): void
    {
        try {
            $enrollments = Enrollment::where('training_group_id', $event->session->training_group_id)
                ->where('status', 'active')
                ->with('participant')
                ->get();

            foreach ($enrollments as $enrollment) {
                $this->notificationService->sendSimple(
                    type: 'session_cancelled',
                    recipientId: $enrollment->participant_id,
                    recipientType: 'participant',
                    data: [
                        'session_date' => $event->session->session_date->format('Y-m-d'),
                        'start_time' => $event->session->start_time,
                        'group_name' => $event->session->group->name_ar ?? '',
                        'reason' => $event->reason,
                    ],
                );
            }
        } catch (\Throwable $e) {
            Log::error('NotifySessionCancellation failed: ' . $e->getMessage(), [
                'session_id' => $event->session->id,
            ]);
        }
    }

    public function failed(SessionCancelled $event, \Throwable $exception): void
    {
        Log::critical('NotifySessionCancellation PERMANENTLY FAILED', [
            'session_id' => $event->session->id,
            'error' => $exception->getMessage(),
        ]);
    }
}
