const admin = require("firebase-admin");
const { query } = require("../../../database/dbpromise");

// FCM initialized flag
let fcmInitialized = false;
let fcmApp = null;

/**
 * Initialize Firebase Admin SDK
 */
async function initializeFCM(fcmConfig) {
  try {
    if (!fcmConfig?.fcm_projectId) {
      console.log("⚠️ FCM config not found");
      return false;
    }

    const serviceAccount = {
      projectId: fcmConfig.fcm_projectId,
      clientEmail: fcmConfig.fcm_clientEmail,
      privateKey: fcmConfig.fcm_privateKey?.replace(/\\n/g, "\n"),
    };

    if (!fcmInitialized) {
      fcmApp = admin.initializeApp({
        credential: admin.credential.cert(serviceAccount),
      });
      fcmInitialized = true;
      console.log("✅ Firebase Admin SDK initialized");
    }

    return true;
  } catch (error) {
    console.error("❌ Error initializing FCM:", error.message);
    return false;
  }
}

/**
 * Send FCM push notification
 */
async function sendFcmPushNotification({
  fcm_projectId,
  fcm_clientEmail,
  fcm_privateKey,
  tokens,
  notification,
}) {
  try {
    // Initialize FCM if not already done
    const initialized = await initializeFCM({
      fcm_projectId,
      fcm_clientEmail,
      fcm_privateKey,
    });

    if (!initialized) {
      return {
        success: false,
        msg: "FCM initialization failed",
      };
    }

    if (!tokens || !Array.isArray(tokens) || tokens.length === 0) {
      return {
        success: false,
        msg: "No tokens provided",
      };
    }

    // Prepare message
    const message = {
      notification: {
        title: notification.title || "New Message",
        body: notification.body || "",
        icon: notification.icon || "/logo192.png",
        click_action: notification.click_action || "FLUTTER_NOTIFICATION_CLICK",
      },
      data: notification.data || {},
      tokens,
    };

    // Send multicast message
    const response = await admin.messaging().sendEachForMulticast(message);

    console.log(`📱 FCM Notification sent:
      Success: ${response.successCount}
      Failure: ${response.failureCount}`);

    // Handle failed tokens
    if (response.failureCount > 0) {
      const failedTokens = [];
      response.responses.forEach((resp, idx) => {
        if (!resp.success) {
          failedTokens.push(tokens[idx]);
          console.log(`❌ Failed to send to token ${tokens[idx]}: ${resp.error?.message}`);
        }
      });

      // Remove invalid tokens from database
      if (failedTokens.length > 0) {
        await query(
          `DELETE FROM fcm_tokens WHERE token IN (?)`,
          [failedTokens]
        );
        console.log(`🗑️ Removed ${failedTokens.length} invalid tokens`);
      }
    }

    return {
      success: true,
      msg: "Notifications sent successfully",
      successCount: response.successCount,
      failureCount: response.failureCount,
    };
  } catch (error) {
    console.error("❌ Error sending FCM notification:", error.message);
    return {
      success: false,
      msg: error.message,
    };
  }
}

/**
 * Generate notification object from message
 */
const generateNotificationFromMessage = (msg, langData = {}) => {
  try {
    const senderName = msg.senderName || "Unknown";
    const messageText = msg.message || "";
    const chatId = msg.chatId || "";

    return {
      title: langData.notificationTitle || `New message from ${senderName}`,
      body: messageText.substring(0, 100) + (messageText.length > 100 ? "..." : ""),
      icon: "/logo192.png",
      click_action: `FLUTTER_NOTIFICATION_CLICK?chatId=${chatId}`,
      data: {
        chatId,
        senderName,
        timestamp: Date.now().toString(),
        type: msg.type || "text",
      },
    };
  } catch (error) {
    console.error("Error generating notification:", error);
    return {
      title: "New Message",
      body: "You have a new message",
    };
  }
};

/**
 * Extract FCM tokens for a user
 */
async function extractTokens(params) {
  try {
    const { uid, userType = "user" } = params;

    const tokens = await query(
      `SELECT token FROM fcm_tokens WHERE uid = ?`,
      [uid]
    );

    return {
      success: true,
      tokens: tokens.map(t => t.token),
    };
  } catch (error) {
    console.error("Error extracting tokens:", error);
    return {
      success: false,
      msg: error.message,
      tokens: [],
    };
  }
}

/**
 * Process web push message notification
 */
async function processWebPushMessageNotificaion({
  uid,
  message,
  user,
  sessionId,
  origin,
  chatId,
}) {
  try {
    // Get FCM config from database
    const [fcmData] = await query(
      `SELECT fcm_projectId, fcm_clientEmail, fcm_privateKey FROM web_private`,
      []
    );

    if (!fcmData?.fcm_projectId) {
      return {
        success: false,
        msg: "FCM not configured",
      };
    }

    // Generate notification
    const notification = generateNotificationFromMessage({
      senderName: user?.name || "Unknown",
      message: message?.text || message?.caption || "",
      chatId,
      type: message?.type || "text",
    });

    // Get user tokens
    const tokenResult = await extractTokens({ uid });
    if (!tokenResult.success || tokenResult.tokens.length === 0) {
      return {
        success: false,
        msg: "No tokens found for user",
      };
    }

    // Send notification
    return await sendFcmPushNotification({
      fcm_projectId: fcmData.fcm_projectId,
      fcm_clientEmail: fcmData.fcm_clientEmail,
      fcm_privateKey: fcmData.fcm_privateKey,
      tokens: tokenResult.tokens,
      notification,
    });
  } catch (error) {
    console.error("Error processing web push notification:", error);
    return {
      success: false,
      msg: error.message,
    };
  }
}

/**
 * Check if web push is enabled
 */
function checkWebPush() {
  return {
    success: true,
    msg: "Web push notification plugin is active",
  };
}

module.exports = {
  checkWebPush,
  sendFcmPushNotification,
  generateNotificationFromMessage,
  processWebPushMessageNotificaion,
  extractTokens,
  initializeFCM,
};
