import { Types } from 'mongoose';
import { messaging } from '@/shared/config/firebase';

interface SendFCMNotificationParams {
  token: string;
  title: string;
  body: string;
  imageUrl?: string;
  data?: Record<string, string | Types.ObjectId>;
}

/**
 * Sends a push notification to a device via FCM.
 */
export const sendFCMNotification = async ({
  token,
  title,
  body,
  data,
  imageUrl,
}: SendFCMNotificationParams): Promise<void> => {
  const formattedData: Record<string, string> = {};

  for (const key in data)
    if (data[key] instanceof Types.ObjectId)
      formattedData[key] = data[key].toHexString();
    else formattedData[key] = String(data[key]);

  const message = {
    token,
    notification: {
      title,
      body,
      ...(imageUrl ? { image: imageUrl } : {}),
    },
    data: formattedData,
  };

  try {
    const response = await messaging.send(message);
    console.log('✅ FCM notification sent:', response);
  } catch (error) {
    console.error('❌ Error sending FCM notification:', error.errorInfo.message);
  }
};
