<?php

namespace App\Domain\Attendance\Listeners;

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

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

    public function handle(ParticipantAbsent $event): void
    {
        try {
            $participant = $event->record->subject;
            if (!$participant || $event->record->subject_type !== 'participant') {
                return;
            }

            $guardians = $participant->guardians ?? collect();
            $primaryGuardian = $guardians->first();

            if (!$primaryGuardian) {
                return;
            }

            $this->notificationService->sendSimple(
                type: 'participant_absent',
                recipientId: $primaryGuardian->id,
                recipientType: 'guardian',
                data: [
                    'participant_name' => $participant->person->name_ar ?? '',
                    'session_date' => $event->record->session?->session_date?->format('Y-m-d'),
                    'group_name' => $event->record->session?->group?->name_ar ?? '',
                ],
            );
        } catch (\Throwable $e) {
            Log::error('NotifyGuardianOfAbsence failed: ' . $e->getMessage(), [
                'record_id' => $event->record->id,
            ]);
        }
    }

    public function failed(ParticipantAbsent $event, \Throwable $exception): void
    {
        Log::critical('NotifyGuardianOfAbsence PERMANENTLY FAILED', [
            'record_id' => $event->record->id,
            'error' => $exception->getMessage(),
        ]);
    }
}
