const { Server } = require("socket.io");
const {
  insertMessage,
  getMessages,
  insertContact,
  getContacts,
} = require("../db/db");
const filter = require("../utils/filter");
const { verifyJwtToken } = require("../auth/jwt");
const console = require("node:console");

function initializeSocket(io) {
  io.use((socket, next) => {
    const token = socket.handshake.auth.token;
    if (!token) {
      console.log("(socket) Not logged in");
      return next(new Error("(socket) Not logged in"));
    }

    try {
      const { username, user_id } = verifyJwtToken(token);
      if (!username || !user_id) {
        console.log("(socket) Invalid token payload");
        return next(new Error("(socket) Invalid token payload"));
      }

      socket.username = filter(username);
      socket.user_id = user_id;
      console.log(
        `(socket) socket id: ${socket.id}, username: ${username}, user_id: ${user_id}`,
      );
      next();
    } catch (error) {
      console.error("(socket) Token verification failed:", error.message);
      next(new Error("(socket) Invalid token"));
    }
  });

  io.on("connection", async (socket) => {
    const username = filter(socket.username);
    if (!username) {
      socket.on("disconnect", () => {
        console.log(
          "(socket)",
          socket.id,
          " disconnected due to: invalid username/token",
        );
      });
      return;
    }
    socket.join(username); // join username room

    socket.on("chat message", async (msg) => {
      const { message } = msg;
      let { recipient } = msg;
      recipient = filter(recipient);
      const sender = username;
      if (!message || !recipient) {
        return;
      }

      const insertedMessage = await insertMessage(username, recipient, message);
      const { message_id, timestamp } = insertedMessage;
      console.log("(socket) received from chat message", msg);

      io.to(username).to(recipient).emit("chat message", {
        sender,
        message,
        recipient,
        message_id,
      });
      console.log("(socket) sent on 'chat message' socket: ", {
        sender,
        message,
        recipient,
        timestamp,
        message_id,
      });
    });

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

module.exports = { initializeSocket };
