<?php

namespace App\Traits\Notification;

use App\Models\PushNotification;
use Livewire\Attributes\On;

trait WithSubscribeNotification
{
    #[On('notification:subscribe')]
    public function notificationSubscribe(string $subscription)
    {
        $subscription = json_decode($subscription, true);

        $isExist = PushNotification::where('user_id', auth()->id())
            ->whereJsonContains('subscriptions->keys->auth', $subscription['keys']['auth'])
            ->first();

        if ($isExist) {
            return;
        }

        $userId = auth()->id();

        $encodedSubscription = json_encode($subscription);
        PushNotification::updateOrCreate(
            [
                'user_id' => $userId,
                'subscriptions' => $encodedSubscription,
            ],
            ['subscriptions' => $encodedSubscription],
        );
    }
}
