import { subscribe, unsubscribe } from "./api";

export const STORAGE_KEY = "notification_enabled";

export async function registerNotification() {
  const permission = await Notification.requestPermission();
  if (permission !== "granted") {
    return {
      error: "E_PERMISSION_DENIED",
    };
  }
  if (!("serviceWorker" in navigator) || !("PushManager" in window)) {
    return {
      error: "E_UNSUPPORTED",
    };
  }
  const registration = await navigator.serviceWorker.ready;
  try {
    const subscription = await registration.pushManager.subscribe({
      userVisibleOnly: true,
      applicationServerKey: import.meta.env.VITE_PUBLIC_VAPID_KEY,
    });
    const data = await subscribe(subscription);
    // Store to local storage
    localStorage.setItem(STORAGE_KEY, data.id?.toString());
    return subscription;
  } catch (err) {
    return {
      error: "Erreur : " + err,
    };
  }
}

export function isNotificationEnabled() {
  return !!localStorage.getItem(STORAGE_KEY);
}

export async function unregisterNotification() {
  const subscriptionId = localStorage.getItem(STORAGE_KEY);
  if (!subscriptionId) {
    return {
      error: "E_NOT_REGISTERED",
    };
  }
  await unsubscribe(subscriptionId);
  localStorage.removeItem(STORAGE_KEY);
}
