const {onRequest} = require("firebase-functions/v2/https");
const {onDocumentCreated} = require("firebase-functions/v2/firestore");
const admin = require("firebase-admin");

admin.initializeApp();
const db = admin.firestore();

// HTTP test
exports.helloWorld = onRequest((req, res) => {
  res.send("Hello from Firebase!");
});

// Trigger on new ride created
exports.onRideCreated = onDocumentCreated("rides/{rideId}", async (event) => {
  const ride = event.data.data();
  const rideId = event.params.rideId;

  console.log("🚕 New ride created:", rideId);

  if (ride.driverId) {
    console.log("Ride already has driver — skipping.");
    return;
  }

  const driversSnap = await db
      .collection("users")
      .where("role", "==", "driver")
      .where("active", "==", true)
      .get();

  if (driversSnap.empty) {
    console.log("❌ No drivers are active right now.");
    return;
  }

  const messaging = admin.messaging();
  let count = 0;

  for (const doc of driversSnap.docs) {
    const driver = doc.data();

    if (!driver.fcmToken) continue;

    const message = {
      token: driver.fcmToken,
      notification: {
        title: "New Ride Request",
        body:
          `${ride.sourceLocationName} ➝ ` +
          `${ride.destinationLocationName}`.slice(0, 80), // max-len safe
      },
      data: {
        rideId,
        type: "NEW_RIDE",
      },
    };

    try {
      await messaging.send(message);
      count++;
    } catch (err) {
      console.log("FCM Error:", err);
    }
  }

  console.log(`📨 Sent ride request to ${count} drivers.`);
});
