<?php

namespace App\Domain\Attendance\Listeners;

use App\Domain\Attendance\Services\AttendanceGenerationService;
use App\Domain\Training\Events\ParticipantStatusChanged;
use App\Domain\Training\Models\Enrollment;
use Illuminate\Contracts\Queue\ShouldQueue;

class RegenerateAttendanceOnReactivation implements ShouldQueue
{
    public function __construct(
        private AttendanceGenerationService $generationService,
    ) {}

    public function handle(ParticipantStatusChanged $event): void
    {
        if ($event->newStatus !== 'active') {
            return;
        }

        if (!in_array($event->oldStatus, ['suspended', 'frozen', 'inactive'])) {
            return;
        }

        $enrollments = Enrollment::where('participant_id', $event->participant->id)
            ->where('status', 'active')
            ->get();

        foreach ($enrollments as $enrollment) {
            $this->generationService->generateForEnrollment($enrollment);
        }
    }
}
