<?php

namespace App\Domain\Training\Listeners;

use App\Domain\Training\Events\EnrollmentCancelled;
use App\Domain\Training\Events\EnrollmentCreated;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

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

            $activeCount = $group->enrollments()
                ->where('status', 'active')
                ->count();

            $group->update(['current_count' => $activeCount]);
        } catch (\Throwable $e) {
            Log::error('UpdateGroupCount failed: ' . $e->getMessage(), [
                'enrollment_id' => $event->enrollment->id,
            ]);
        }
    }

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