<?php

namespace App\Domain\Attendance\Listeners;

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

class NotifyThresholdBreach implements ShouldQueue
{
    public function __construct(
        private NotificationService $notificationService,
    ) {}

    public function handle(AttendanceThresholdBreached $event): void
    {
        try {
            $this->notificationService->sendSimple(
                type: 'attendance_threshold_breached',
                recipientId: $event->participant->id,
                recipientType: 'participant',
                data: [
                    'participant_name' => $event->participant->person->name_ar ?? '',
                    'rate' => round($event->rate, 1),
                    'threshold' => $event->threshold,
                ],
                priority: 'high',
            );
        } catch (\Throwable $e) {
            Log::error('NotifyThresholdBreach failed: ' . $e->getMessage(), [
                'participant_id' => $event->participant->id,
            ]);
        }
    }

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