'use strict'

console.log('SW /worker/index.js Loaded...')

self.addEventListener('fetch', (event) => {
    try {
        if (event.request.url.includes('/api/auth/callback/')) {
            // Use network only strategy for auth routes, or bypass SW completely
            event.respondWith(fetch(event.request));
            return;
        }
        // other caching strategies...
    } catch (error) {
        console.error(error)
    }
});

self.addEventListener('push', function (event) {
    console.log('SW: New push message', event)
    if (!(self.Notification && self.Notification.permission === 'granted')) {
        return
    }
    const data = JSON.parse(event.data.text())
    console.log('SW: Push data', data)
    actions: [
        //font awesome icons
        { action: 'accept', title: 'Accept', icon: 'fa fa-check' },
        { action: 'decline', title: 'Decline', icon: 'fa fa-times' }
    ]
    event.waitUntil(
        registration.showNotification(data.title, {
            body: data.message,
            icon: '/favicon.ico',
            actions: [{ action: 'close', title: 'Close', icon: 'fa fa-times' }],
            data: data.url,
        })
    )
})

self.addEventListener('notificationclick', function (event) {
    console.log('Notification click: tag', event.notification.tag, 'action', event.action)
    event.notification.close()
    switch (event.action) {
        case 'accept':
            console.log('User accepted the action.');
            // handle acceptance
            break;
        case 'decline':
            console.log('User declined the action.');
            // handle decline
            break;
        default:
            // handle other cases
            break;
    }
    console.log(event)
    event.waitUntil(
        clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (clientList) {
            if (clientList.length > 0) {
                let client = clientList[0]
                for (let i = 0; i < clientList.length; i++) {
                    if (clientList[i].focused) {
                        client = clientList[i]
                    }
                }
                return client.focus()
            }
            return clients.openWindow('/')
        })
    )
})

// self.addEventListener('pushsubscriptionchange', function(event) {
//   event.waitUntil(
//       Promise.all([
//           Promise.resolve(event.oldSubscription ? deleteSubscription(event.oldSubscription) : true),
//           Promise.resolve(event.newSubscription ? event.newSubscription : subscribePush(registration))
//               .then(function(sub) { return saveSubscription(sub) })
//       ])
//   )
// })