import express from "express";
import http from "http";
import { Server } from "socket.io";
import cors from "cors";

const app = express();
app.use(cors());

const server = http.createServer(app);
const io = new Server(server, {
  cors: { origin: "*" }
});

io.on("connection", (socket) => {
  console.log("🔗 User connected:", socket.id);

  socket.on("call-user", (data) => {
    io.to(data.to).emit("incoming-call", { from: socket.id, offer: data.offer });
  });

  socket.on("answer-call", (data) => {
    io.to(data.to).emit("call-accepted", { from: socket.id, answer: data.answer });
  });

  socket.on("ice-candidate", (data) => {
    io.to(data.to).emit("ice-candidate", data.candidate);
  });

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

server.listen(3000, () => {
  console.log("🚀 Signaling Server running on port 3000");
});
