
const { Expo } = require('expo-server-sdk');

// Create a new Expo SDK client
// optionally providing an access token if you have enabled push security
const expo = new Expo();

/**
 * Send push notifications to an array of tokens
 * @param {string[]} tokens - Array of Expo Push Tokens
 * @param {string} title - Notification Title
 * @param {string} body - Notification Body
 * @param {object} data - Optional data payload
 */
const sendPushNotifications = async (tokens, title, body, data = {}) => {
  const messages = [];

  for (const token of tokens) {
    // Check if token is valid
    if (!Expo.isExpoPushToken(token)) {
      console.error(`Push token ${token} is not a valid Expo push token`);
      continue;
    }

    messages.push({
      to: token,
      sound: 'default',
      title: title,
      body: body,
      data: data,
      channelId: 'default', // Check usePushNotifications.js 'default' channel
      priority: 'high',
    });
  }

  // Batch notifications
  const chunks = expo.chunkPushNotifications(messages);
  const tickets = [];

  for (const chunk of chunks) {
    try {
      const ticketChunk = await expo.sendPushNotificationsAsync(chunk);
      tickets.push(...ticketChunk);
    } catch (error) {
      console.error('Error sending push notification chunk:', error);
    }
  }

  // Handle receipts (optional, for later debugging)
  return tickets;
};

/**
 * Broadcast a push notification to all users who have an expo_push_token
 * @param {string} title - Notification Title
 * @param {string} body - Notification Body
 * @param {object} data - Optional deep linking data
 */
const broadcastPushNotification = async (title, body, data = {}) => {
  try {
    const db = require('../db');
    const result = await db.query("SELECT expo_push_token FROM users WHERE expo_push_token IS NOT NULL AND expo_push_token != ''");
    
    if (result.rows.length === 0) {
      console.log('No push tokens found for broadcasting.');
      return [];
    }

    const tokens = result.rows.map(row => row.expo_push_token);
    console.log(`Broadcasting push notification to ${tokens.length} users...`);
    
    return await sendPushNotifications(tokens, title, body, data);
  } catch (error) {
    console.error('Error in broadcastPushNotification:', error);
    return [];
  }
};

module.exports = {
  sendPushNotifications,
  broadcastPushNotification
};
