<?php

namespace App\Domain\Training\Listeners;

use App\Domain\Attendance\Services\AttendanceGenerationService;
use App\Domain\Training\Events\SessionCreated;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class GenerateSessionAttendance implements ShouldQueue
{
    public function __construct(
        private AttendanceGenerationService $attendanceService,
    ) {}

    public function handle(SessionCreated $event): void
    {
        try {
            $this->attendanceService->generateForSession($event->session);
        } catch (\Throwable $e) {
            Log::error('GenerateSessionAttendance failed: ' . $e->getMessage(), [
                'session_id' => $event->session->id,
                'group_id' => $event->session->training_group_id,
            ]);
        }
    }

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