<?php

namespace App\Domain\Training\Listeners;

use App\Domain\Training\Events\EnrollmentCancelled;
use App\Domain\Training\Events\WaitlistSpotAvailable;
use App\Domain\Training\Models\Waitlist;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class ProcessWaitlist implements ShouldQueue
{
    public function handle(EnrollmentCancelled $event): void
    {
        try {
            $group = $event->enrollment->group;
            if (!$group) {
                return;
            }

            if ($group->current_count >= $group->max_capacity) {
                return;
            }

            $nextInLine = Waitlist::where('training_group_id', $group->id)
                ->where('status', 'waiting')
                ->orderBy('position')
                ->first();

            if ($nextInLine) {
                $nextInLine->update(['status' => 'notified', 'notified_at' => now()]);
                WaitlistSpotAvailable::dispatch($group, $nextInLine);
            }
        } catch (\Throwable $e) {
            Log::error('ProcessWaitlist failed: ' . $e->getMessage(), [
                'enrollment_id' => $event->enrollment->id,
            ]);
        }
    }

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