<?php

namespace App\Domain\Training\Listeners;

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

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

    public function handle(SessionCompleted $event): void
    {
        try {
            $this->notificationService->sendToRole(
                type: 'session_completed',
                role: 'head_trainer',
                data: [
                    'group_name' => $event->session->trainingGroup?->name_ar ?? '',
                    'session_date' => $event->session->session_date?->format('Y-m-d') ?? $event->session->date?->format('Y-m-d') ?? '',
                    'attendance_count' => (string) ($event->session->attendanceRecords()->whereIn('status', ['present', 'late'])->count()),
                    'total_count' => (string) ($event->session->attendanceRecords()->count()),
                ],
            );
        } catch (\Throwable $e) {
            Log::error('SendSessionCompletedNotification failed: ' . $e->getMessage(), [
                'session_id' => $event->session->id,
            ]);
        }
    }

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