<?php

namespace App\Domain\Attendance\Listeners;

use App\Domain\Attendance\Events\AttendanceThresholdBreached;
use App\Domain\Participant\Services\ParticipantService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class SuspendOnThreshold implements ShouldQueue
{
    public function __construct(
        private ParticipantService $participantService,
    ) {}

    public function handle(AttendanceThresholdBreached $event): void
    {
        try {
            $participant = $event->participant;

            if ($participant->status === 'suspended' || $participant->status === 'blacklisted') {
                return;
            }

            $statusValue = $participant->status instanceof \BackedEnum
                ? $participant->status->value
                : (string) $participant->status;

            if (!in_array($statusValue, ['active'])) {
                return;
            }

            $this->participantService->changeStatus(
                $participant,
                'suspended',
                "تجاوز حد الغياب المسموح - نسبة الحضور: {$event->rate}%",
            );
        } catch (\Throwable $e) {
            Log::error('SuspendOnThreshold failed: ' . $e->getMessage(), [
                'participant_id' => $event->participant->id,
            ]);
        }
    }

    public function failed(AttendanceThresholdBreached $event, \Throwable $exception): void
    {
        Log::critical('SuspendOnThreshold PERMANENTLY FAILED', [
            'participant_id' => $event->participant->id,
            'error' => $exception->getMessage(),
        ]);
    }
}
