<?php

namespace App\Domain\Training\Listeners;

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

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

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

            if ($enrollment->status !== 'active') {
                return;
            }

            $this->attendanceService->generateForEnrollment($enrollment);
        } catch (\Throwable $e) {
            Log::error('GenerateAttendanceRecords failed: ' . $e->getMessage(), [
                'enrollment_id' => $event->enrollment->id,
            ]);
        }
    }

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