/**
 * Fusion Technician Portal - Service Worker for Push Notifications
 * Handles push events and notification clicks.
 */

self.addEventListener('push', function(event) {
    if (!event.data) return;

    var data;
    try {
        data = event.data.json();
    } catch (e) {
        data = {title: 'New Notification', body: event.data.text()};
    }

    var options = {
        body: data.body || '',
        icon: '/fusion_authorizer_portal/static/description/icon.png',
        badge: '/fusion_authorizer_portal/static/description/icon.png',
        tag: 'tech-task-' + (data.task_id || 'general'),
        renotify: true,
        data: {
            url: data.url || '/my/technician',
            taskId: data.task_id,
            taskType: data.task_type,
        },
        actions: [],
    };

    // Add contextual actions based on task type
    if (data.url) {
        options.actions.push({action: 'view', title: 'View Task'});
    }
    if (data.task_type === 'delivery' || data.task_type === 'repair') {
        options.actions.push({action: 'navigate', title: 'Navigate'});
    }

    event.waitUntil(
        self.registration.showNotification(data.title || 'Fusion Technician', options)
    );
});

self.addEventListener('notificationclick', function(event) {
    event.notification.close();

    var url = '/my/technician';
    if (event.notification.data && event.notification.data.url) {
        url = event.notification.data.url;
    }

    if (event.action === 'navigate' && event.notification.data && event.notification.data.taskId) {
        // Open Google Maps for the task (will redirect through portal)
        url = '/my/technician/task/' + event.notification.data.taskId;
    }

    event.waitUntil(
        clients.matchAll({type: 'window', includeUncontrolled: true}).then(function(clientList) {
            // Focus existing window if open
            for (var i = 0; i < clientList.length; i++) {
                var client = clientList[i];
                if (client.url.indexOf('/my/technician') !== -1 && 'focus' in client) {
                    client.navigate(url);
                    return client.focus();
                }
            }
            // Open new window
            if (clients.openWindow) {
                return clients.openWindow(url);
            }
        })
    );
});

// Keep service worker alive
self.addEventListener('activate', function(event) {
    event.waitUntil(self.clients.claim());
});
