import { admin } from '../config/firebase';
import { Message } from 'firebase-admin/messaging';

export interface NotificationPayload {
  title: string;
  body: string;
  data?: { [key: string]: string };
  imageUrl?: string;
}

export interface NotificationOptions {
  priority?: 'high' | 'normal';
  sound?: string;
  badge?: number;
  clickAction?: string;
}

class NotificationService {
  /**
   * Send notification to a single device
   */
  async sendToDevice(
    token: string,
    payload: NotificationPayload,
    options: NotificationOptions = {}
  ): Promise<string> {
    try {
      const message: Message = {
        token,
        notification: {
          title: payload.title,
          body: payload.body,
          imageUrl: payload.imageUrl,
        },
        data: payload.data || {},
        android: {
          priority: options.priority || 'high',
          notification: {
            sound: options.sound || 'default',
            clickAction: options.clickAction,
          },
        },
        apns: {
          payload: {
            aps: {
              sound: options.sound || 'default',
              badge: options.badge,
            },
          },
        },
      };

      const response = await admin.messaging().send(message);
      console.log('✅ Notification sent successfully:', response);
      return response;
    } catch (error: any) {
      // Handle specific Firebase messaging errors
      if (error?.errorInfo?.code === 'messaging/registration-token-not-registered') {
        console.warn(
          '⚠️ Device token is no longer valid (user may have uninstalled the app or token expired)'
        );
        // Re-throw with a more specific error for upstream handling
        const tokenError = new Error('INVALID_TOKEN');
        (tokenError as any).originalError = error;
        throw tokenError;
      }

      if (error?.errorInfo?.code === 'messaging/invalid-registration-token') {
        console.warn('⚠️ Device token format is invalid');
        const tokenError = new Error('INVALID_TOKEN');
        (tokenError as any).originalError = error;
        throw tokenError;
      }

      // Log other errors normally
      console.error('❌ Error sending notification:', error);
      throw error;
    }
  }
}

export default new NotificationService();
