<?php

namespace App\Services;

use App\Enums\Role;
use App\Models\User;
use App\Notifications\WebPushNotification;
use Illuminate\Support\Facades\Log;

class NotificationService
{
    /**
     * @param  array<Role>  $roles
     */
    public static function notify(array $roles, string $title, string $body, string $url, ?User $additionalUser = null): void
    {
        $roleLabels = array_map(fn (Role $role) => $role->label(), $roles);

        $users = User::query()
            ->select(['id'])
            ->where('is_active', true)
            ->whereHas('roles', fn ($q) => $q->whereIn('name', $roleLabels))
            ->get();

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

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

                $user->notify(new WebPushNotification($title, $body));
            } catch (\Exception $e) {
                Log::error("Gagal mengirim notifikasi ke user {$user->id}: {$e->getMessage()}");
            }
        });
    }
}
