/* eslint-disable no-undef */
importScripts('https://www.gstatic.com/firebasejs/11.6.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/11.6.0/firebase-messaging-compat.js');

const API_PREFIX = '/idp-api';

async function loadPublicSettings() {
  const response = await fetch(`${API_PREFIX}/settings/public`, { credentials: 'same-origin' });
  if (!response.ok) {
    throw new Error('Не удалось загрузить публичные настройки Firebase');
  }
  const payload = await response.json();
  const map = Object.fromEntries((payload.settings ?? []).map((item) => [item.key, item.value]));
  return map;
}

function isEnabled(value) {
  return ['true', '1', 'yes'].includes(String(value ?? '').trim().toLowerCase());
}

async function initFirebaseMessaging() {
  const settings = await loadPublicSettings();
  if (!isEnabled(settings.FIREBASE_PUSH_ENABLED)) return;

  const projectId = settings.FIREBASE_PROJECT_ID?.trim();
  const apiKey = settings.FIREBASE_WEB_API_KEY?.trim();
  const appId = settings.FIREBASE_WEB_APP_ID?.trim();
  const messagingSenderId = settings.FIREBASE_WEB_MESSAGING_SENDER_ID?.trim();

  if (!projectId || !apiKey || !appId || !messagingSenderId) return;

  firebase.initializeApp({
    apiKey,
    authDomain: `${projectId}.firebaseapp.com`,
    projectId,
    messagingSenderId,
    appId
  });

  const messaging = firebase.messaging();
  messaging.onBackgroundMessage((payload) => {
    const title = payload.notification?.title || payload.data?.title || 'Уведомление';
    const options = {
      body: payload.notification?.body || payload.data?.message || '',
      data: payload.data ?? {}
    };
    self.registration.showNotification(title, options);
  });
}

self.addEventListener('install', (event) => {
  event.waitUntil(self.skipWaiting());
});

self.addEventListener('activate', (event) => {
  event.waitUntil(self.clients.claim());
});

self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  event.waitUntil(
    self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clients) => {
      const existing = clients.find((client) => 'focus' in client);
      if (existing) {
        return existing.focus();
      }
      return self.clients.openWindow('/');
    })
  );
});

initFirebaseMessaging().catch(() => undefined);
