'use client'; // All notification features share one browser permission and root service worker. export async function syncSitePush(userId: string) { const configResponse = await fetch('/api/commission/push-subscription', { cache: 'no-store' }); if (!configResponse.ok) throw new Error('push-config-failed'); const config = await configResponse.json() as { publicKey: string; canAdmin: boolean }; const registration = await navigator.serviceWorker.register('/commission-push-sw.js', { scope: '/' }); const subscription = await registration.pushManager.getSubscription() ?? await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: config.publicKey }); const data = subscription.toJSON(); const registrations = [ { url: '/api/comments/push-subscription', body: data }, { url: '/api/commission/push-subscription', body: { ...data, scope: config.canAdmin ? 'admin' : 'customer' } }, ]; const responses = await Promise.all(registrations.map(feature => fetch(feature.url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(feature.body) }))); if (responses.some(response => !response.ok)) throw new Error('push-subscription-failed'); sessionStorage.setItem(`site-push-synced-${userId}`, '1'); }