<?php

namespace App\Services;

use App\Enums\Role;
use App\Models\User;
use App\Notifications\WebPushNotification;
use Illuminate\Support\Collection;
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, ?User $except = null): void
    {
        $except ??= auth()->user();

        $roleValues = array_map(fn (Role $role) => $role->value, $roles);

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

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

        $users->each(function (User $user) use ($title, $body, $url) {
            self::sendNotification($user, $title, $body, $url);
        });
    }

    /**
     * @param  Collection<int, User>|array<int, User>  $users
     */
    public static function notifyUsers(Collection|array $users, string $title, string $body, string $url): void
    {
        $users = $users instanceof Collection ? $users : collect($users);

        $users->each(function (User $user) use ($title, $body, $url) {
            self::sendNotification($user, $title, $body, $url);
        });
    }

    private static function sendNotification(User $user, string $title, string $body, string $url): void
    {
        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()}");
        }
    }
}
