import { app, getMessaging, getToken, onMessage, isSupported } from '@/lib/firebase';
import api from './api';

const VAPID_KEY = process.env.NEXT_PUBLIC_FIREBASE_VAPID_KEY;

class NotificationService {
  private currentToken: string | null = null;

  async requestPermissionAndRegister(): Promise<boolean> {
    try {
      // Check if messaging is supported in this browser
      const supported = await isSupported();
      if (!supported) {
        console.log('[Notifications] Firebase messaging not supported in this browser');
        return false;
      }

      if (!VAPID_KEY) {
        console.warn('[Notifications] VAPID key not configured');
        return false;
      }

      // Request notification permission
      const permission = await Notification.requestPermission();
      if (permission !== 'granted') {
        console.log('[Notifications] Permission denied');
        return false;
      }

      // Register service worker
      const registration = await navigator.serviceWorker.register(
        '/firebase-messaging-sw.js'
      );

      // Get FCM token
      const messaging = getMessaging(app);
      const token = await getToken(messaging, {
        vapidKey: VAPID_KEY,
        serviceWorkerRegistration: registration,
      });

      if (!token) {
        console.warn('[Notifications] No FCM token received');
        return false;
      }

      this.currentToken = token;

      // Register token with backend
      await api.post('/notifications/fcm-token', {
        token,
        device: 'web',
      });

      console.log('[Notifications] FCM token registered');
      return true;
    } catch (error) {
      console.error('[Notifications] Registration failed:', error);
      return false;
    }
  }

  async unregister(): Promise<void> {
    try {
      if (this.currentToken) {
        await api.delete('/notifications/fcm-token', {
          data: { token: this.currentToken },
        });
        this.currentToken = null;
      }
    } catch (error) {
      console.error('[Notifications] Unregister failed:', error);
    }
  }

  setupForegroundHandler(
    callback: (payload: { title: string; body: string; data?: Record<string, string> }) => void
  ): (() => void) | null {
    try {
      const messaging = getMessaging(app);
      const unsubscribe = onMessage(messaging, (payload) => {
        callback({
          title: payload.notification?.title || 'New Notification',
          body: payload.notification?.body || '',
          data: payload.data as Record<string, string>,
        });
      });
      return unsubscribe;
    } catch {
      return null;
    }
  }
}

export const notificationService = new NotificationService();
