// src/pushManager.ts
import apiClient from '@/services/axiosSetup';

const applicationServerKey = ''


function urlBase64ToUint8Array(base64String: string): Uint8Array {

    const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
    const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
    const rawData = window.atob(base64);
    return new Uint8Array([...rawData].map((char) => char.charCodeAt(0)));
}

export async function subscribeUserToPush() {
    const registration = await navigator.serviceWorker.ready;
    let vapid = ''
    if (localStorage.getItem("token")) {
        await apiClient.get('/subscriptions/vapid').then((registration) => {
            vapid = registration.data

        })

        return registration.pushManager.subscribe({
            userVisibleOnly: true,
            applicationServerKey: urlBase64ToUint8Array(vapid),
        });
    }
}
