import { requestApi } from ':src/utils.ts'
import { useEffect } from 'preact/hooks'

async function register() {
	const registration = await navigator.serviceWorker.register('/sw', {
		scope: '/',
		type: 'module',
	})

	// Notification.requestPermission().then((permission) => {
	// if (permission !== 'granted') return

	// registration.showNotification('Notification permission granted', {
	// 	body: 'Notification is ok.',
	// })
	// })

	async function getSubscription() {
		const currentSubscription = await registration.pushManager
			.getSubscription()
		if (currentSubscription) return currentSubscription

		const applicationServerKey = await requestApi<void, string>(
			'webpush/vapid',
			'GET',
		)

		return await registration.pushManager.subscribe({
			userVisibleOnly: true,
			applicationServerKey,
		})
	}

	try {
		if (registration.active === null) return
		const subscription = await getSubscription()
		await requestApi('webpush/subscription', 'POST', subscription)
	} catch (cause) {
		console.error('Push subscription is not available', { cause })
	}
}

export default function RegisterServiceWorker() {
	useEffect(() => {
		if ('serviceWorker' in navigator) register()
	}, [])

	return null
}
