<?php

namespace App\Listeners;

use App\Enums\GuestNotificationAudience;
use App\Events\GuestNotificationCreated;
use App\Jobs\SendGuestPushNotificationBatch;
use App\Models\PushSubscription;

class DispatchGuestNotificationPush
{
    public function handle(GuestNotificationCreated $event): void
    {
        if (! config('push.enabled')) {
            return;
        }

        $notification = $event->notification;
        $query = PushSubscription::query()
            ->where('event_id', $notification->event_id)
            ->where('status', 'active');

        if ($notification->audience_scope === GuestNotificationAudience::GUEST && $notification->target_identifier) {
            $target = $notification->target_identifier;
            $query->where(function ($builder) use ($target) {
                $builder->where('guest_identifier', $target)
                    ->orWhere('device_id', $target);
            });
        }

        $subscriptionIds = $query->pluck('id')->all();

        if ($subscriptionIds === []) {
            return;
        }

        foreach (array_chunk($subscriptionIds, 50) as $chunk) {
            SendGuestPushNotificationBatch::dispatch($notification->id, $chunk);
        }
    }
}
