<?php

namespace App\Domain\Notification\Listeners;

use App\Domain\Attendance\Events\AttendanceMarked;
use App\Domain\Notification\Services\PushNotificationService;
use App\Domain\Participant\Models\Participant;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendAttendancePush implements ShouldQueue
{
    public function __construct(private PushNotificationService $pushService) {}

    public function handle(AttendanceMarked $event): void
    {
        $record = $event->record;

        if ($record->subject_type !== 'App\\Domain\\Participant\\Models\\Participant') {
            return;
        }

        $participant = Participant::with('person')->find($record->subject_id);
        if (!$participant) {
            return;
        }

        $name = $participant->person?->name_ar ?? 'المشترك';
        $status = $record->status->value ?? $record->status;

        if (in_array($status, ['present', 'late'])) {
            $title = 'تسجيل حضور ✓';
            $body = "تم تسجيل حضور {$name} في جلسة اليوم";
        } elseif (in_array($status, ['absent', 'no_show'])) {
            $title = 'تسجيل غياب';
            $body = "تم تسجيل غياب {$name} في جلسة اليوم";
        } else {
            return;
        }

        $this->pushService->sendToParticipantGuardians(
            $participant,
            $title,
            $body,
            [
                'type' => 'attendance',
                'route' => '/participants/{participant_uuid}/attendance',
                'participant_uuid' => $participant->uuid,
                'status' => $status,
            ],
            'attendance.marked'
        );
    }
}
