<?php

namespace App\Domain\Training\Listeners;

use App\Domain\Attendance\Models\AttendanceRecord;
use App\Domain\Training\Events\EnrollmentCancelled;
use App\Domain\Training\Models\TrainingSession;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class RemoveAttendanceRecords implements ShouldQueue
{
    public function handle(EnrollmentCancelled $event): void
    {
        try {
            $enrollment = $event->enrollment;

            $futureSessionIds = TrainingSession::where('training_group_id', $enrollment->training_group_id)
                ->where('session_date', '>', today())
                ->pluck('id');

            if ($futureSessionIds->isEmpty()) {
                return;
            }

            AttendanceRecord::whereIn('training_session_id', $futureSessionIds)
                ->where('subject_type', 'participant')
                ->where('subject_id', $enrollment->participant_id)
                ->where('status', 'expected')
                ->delete();
        } catch (\Throwable $e) {
            Log::error('RemoveAttendanceRecords failed: ' . $e->getMessage(), [
                'enrollment_id' => $event->enrollment->id,
            ]);
        }
    }

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