/**
 * FCM 웹 푸시 — frontend_golden / goldenAnalysis 패턴 기반
 * VITE_FIREBASE_* 환경 변수 필요
 */
import { registerFcmToken } from './backendApi';

const FIREBASE_CDN = 'https://www.gstatic.com/firebasejs/10.7.1';

type FirebaseNs = {
  initializeApp: (cfg: Record<string, string>) => { name: string };
  messaging: () => {
    getToken: (opts: { vapidKey: string; serviceWorkerRegistration?: ServiceWorkerRegistration }) => Promise<string>;
    onMessage: (cb: (p: { notification?: { title?: string; body?: string } }) => void) => void;
  };
};

function loadScript(src: string): Promise<void> {
  return new Promise((resolve, reject) => {
    if (document.querySelector(`script[src="${src}"]`)) {
      resolve();
      return;
    }
    const s = document.createElement('script');
    s.src = src;
    s.onload = () => resolve();
    s.onerror = () => reject(new Error(`load failed: ${src}`));
    document.head.appendChild(s);
  });
}

function firebaseConfig() {
  const apiKey = import.meta.env.VITE_FIREBASE_API_KEY as string | undefined;
  if (!apiKey || apiKey === 'YOUR_API_KEY') return null;
  return {
    apiKey,
    authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN ?? '',
    projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID ?? '',
    storageBucket: import.meta.env.VITE_FIREBASE_STORAGE_BUCKET ?? '',
    messagingSenderId: import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID ?? '',
    appId: import.meta.env.VITE_FIREBASE_APP_ID ?? '',
  };
}

export async function initFcmPush(onForeground?: (title: string, body: string) => void): Promise<boolean> {
  const cfg = firebaseConfig();
  const vapidKey = import.meta.env.VITE_FIREBASE_VAPID_KEY as string | undefined;
  if (!cfg || !vapidKey) {
    console.info('[FCM] VITE_FIREBASE_* 미설정 — 푸시 비활성');
    return false;
  }
  if (!('serviceWorker' in navigator) || !('Notification' in window)) return false;

  try {
    await loadScript(`${FIREBASE_CDN}/firebase-app-compat.js`);
    await loadScript(`${FIREBASE_CDN}/firebase-messaging-compat.js`);
    const fb = (window as unknown as { firebase: FirebaseNs }).firebase;
    fb.initializeApp(cfg);
    const reg = await navigator.serviceWorker.register('/firebase-messaging-sw.js');
    const permission = await Notification.requestPermission();
    if (permission !== 'granted') return false;

    const token = await fb.messaging().getToken({ vapidKey, serviceWorkerRegistration: reg });
    if (token) await registerFcmToken(token);

    fb.messaging().onMessage(payload => {
      const title = payload.notification?.title ?? 'GoldenChart';
      const body = payload.notification?.body ?? '';
      onForeground?.(title, body);
    });
    return true;
  } catch (e) {
    console.warn('[FCM] init failed', e);
    return false;
  }
}
