<?php

namespace App\Services;

use App\Models\User;
use App\Notifications\WebPushNotification;

class NotificationService
{
    public static function notify(array $roles, string $title, string $body, string $url, ?User $additionalUser = null): void
    {
        $users = User::query()
            ->where('is_active', true)
            ->whereHas('roles', fn ($q) => $q->whereIn('name', $roles))
            ->get();

        if ($additionalUser && ! $users->contains('id', $additionalUser->id)) {
            $users->push($additionalUser);
        }

        $users->each(function (User $user) use ($title, $body, $url) {
            $user->notifications()->create([
                'title' => $title,
                'body' => $body,
                'url' => $url,
            ]);

            $user->notify(new WebPushNotification($title, $body));
        });
    }
}
