const { Server } = require("socket.io");

module.exports.intializeSocket = (server) => {
  const io = new Server(server, {
    cors: {
      origin: [
        "http://localhost:5173",
      ],
      methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"],
      allowedHeaders: [
        "X-Requested-With",
        "Content-Type",
        "Authorization",
        "Cookie",
      ],
      credentials: true, // Allows cookies and other credentials
    },
    // allowEIO3: true,
    // transports: ["websocket"],
  });

  io.on("connection", (socket) => {
    console.log("a user connected", socket.id);

    // Join a room based on booking ID or user ID
    socket.on("join-room", (roomId) => {
      socket.join(roomId);
      console.log(`User ${socket.id} joined room ${roomId}`);
    });

    // Driver updates location
    socket.on("update-location", async (data) => {
      // data: { bookingId, location: { lat, lng } }
      const { bookingId, location } = data;

      // Broadcast to everyone in the booking room (User, Admin)
      io.to(bookingId).emit("track-driver", {
        bookingId,
        location
      });

      // Optionally update database (throttled or on specific intervals)
      // For now, we just relay the location
      try {
        const Booking = require('./models/booking.model');
        await Booking.findByIdAndUpdate(bookingId, {
          currentLocation: {
            coordinates: [location.lng, location.lat],
            updatedAt: new Date()
          }
        });
      } catch (error) {
        console.error("Error updating location in DB:", error);
      }
    });

    socket.on("disconnect", () => {
      console.log("user disconnected", socket.id);
    });
  });
};
