// import { Server } from "socket.io";
// import {API_BASE_URL} from "../constants/index.js";

// const io = new Server(3002, {
//   cors: {
//     origin: ["http://localhost:3002"],
//     methods: ["GET", "POST"],
//   },
// });

// let loadMessages = [];

// function getMessages() {
//   setInterval(() => {
//     messages();
//     console.log("here is response",loadMessages);
//     io.emit("getMessages", loadMessages);
//   }, 100);
// }

// getMessages();

// async function messages() {
//   try {
//     const response = await fetch(API_BASE_URL + "api/chat-get", {
//       method: "POST",
//       headers: {
//         "Content-Type": "application/json",
//       },
//       body: JSON.stringify({ f: 1 }),
//     });

//     if (!response.ok) {
//       throw new Error(`HTTP error! status: ${response.status}`);
//     }

//     const data = await response.json();
//     loadMessages = data;
//     return data;
//   } catch (error) {
//     console.error("messages() error:", error);

//     // server crash se bachane ke liye safe fallback
//     return loadMessages || { resp: "error", data: [] };
//   }
// }

// async function send(user_id, message){
//   const response = await fetch(API_BASE_URL+"api/chat-send", {
//   method: 'POST',
//     headers: {
//       'Content-Type': 'application/json',
//     },
//     body: JSON.stringify({
//       user_id: user_id,
//       message: message,
//     }),
//   });

//   if (!response.ok) {
//     console.log(response);
//   }
//   const data = await response.json();
//   return data;
// }

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

//   socket.on("send-message", ({ user_id, message }) => {
//       send(user_id, message);
//   });

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

import { Server } from "socket.io";
import { BASE_URL } from "../constants/index.js";

const io = new Server(3002, {
  cors: {
    origin: ["http://localhost:3002"],
    methods: ["GET", "POST"],
  },
});

let loadMessages = [];

function getMessages() {
  setInterval(() => {
    messages();
    console.log("here is response", loadMessages);
    io.emit("getMessages", loadMessages);
  }, 100);
}

getMessages();

async function messages() {
  try {
    const response = await fetch(BASE_URL + "/api/chat-get", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ f: 1 }),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    loadMessages = data;
    return data;
  } catch (error) {
    console.error("messages() error:", error);

    // server crash se bachane ke liye safe fallback
    return loadMessages || { resp: "error", data: [] };
  }
}

async function send(user_id, message) {
  const response = await fetch(BASE_URL + "/api/chat-send", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      user_id: user_id,
      message: message,
    }),
  });

  if (!response.ok) {
    console.log(response);
  }
  const data = await response.json();
  return data;
}

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

  socket.on("send-message", ({ user_id, message }) => {
    send(user_id, message);
  });

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