const chatManager = require("../../game/ChatManager");

module.exports = (io, socket) => {
  socket.on("chat:get_global_history", async () => {
    const history = await chatManager.getGlobalHistory();
    const formattedHistory = history.map((m) => ({
      id: m.id,
      content: m.content,
      senderName: m.sender?.username || "Unknown",
      senderId: m.senderId,
      createdAt: m.createdAt,
      type: m.type,
    }));
    socket.emit("chat:global_history", formattedHistory);
  });
  socket.on("chat:get_global_history", async () => {
    const history = await chatManager.getGlobalHistory();

    const formattedHistory = history.map((m) => ({
      id: m.id,
      content: m.content,
      senderName: m.sender?.username || "Unknown",
      senderId: m.senderId,
      createdAt: m.createdAt,
      type: m.type,
    }));

    socket.emit("chat:global_history", formattedHistory);
  });

  socket.on("chat:send_message", async (payload) => {
    try {
      const senderId = socket.user?.id;
      if (!senderId) return;

      const messageData = await chatManager.saveMessage({
        content: payload.content,
        type: payload.type || "global",
        senderId: senderId,
        receiverId: payload.receiverId,
      });

      if (messageData.type === "global") {
        io.emit("chat:new_message", messageData);
      } else {
        socket
          .to(`user_${payload.receiverId}`)
          .emit("chat:new_message", messageData);
        socket.emit("chat:new_message", messageData);
      }
    } catch (err) {
      console.error(err);
      socket.emit("error", { message: "CHAT_SEND_ERROR" });
    }
  });

  socket.on("chat:get_private_history", async ({ friendId }) => {
    const myId = socket.user?.id;

    if (!myId || !friendId) return;

    const history = await chatManager.getPrivateHistory(myId, friendId);
    const formattedHistory = history.map((m) => ({
      id: m.id,
      content: m.content,
      senderName: m.sender?.username || "Unknown",
      senderId: m.senderId,
      receiverId: m.receiverId,
      createdAt: m.createdAt,
      type: m.type,
    }));
    socket.emit("chat:private_history", formattedHistory);
  });
  socket.on("player:search", async ({ query }) => {
    const senderId = socket.user?.id;
    if (!query || !senderId) return;

    const results = await chatManager.searchPlayers(query, senderId);
    socket.emit("player:search_results", results);
  });
};
