import { type Server as SocketIOServer } from "socket.io";
import {
  ADD_COMMENT_EVENT,
  DELETE_COMMENT_EVENT,
  JOIN_ROOM_EVENT,
} from "./event-const";
import { env } from "@/env";
import { Comment } from "../db/schema";

const log = (message?: any, ...optionalParams: any[]) => {
  if (env.NODE_ENV === "development") {
    console.log(message, ...optionalParams);
  }
};

export const initSocketEvents = (io: SocketIOServer) => {
  io.on("connection", (socket) => {
    log("New client connected:", socket.id);

    socket.on(JOIN_ROOM_EVENT, (articleId: string) => {
      socket.join(articleId);
      log(`Client ${socket.id} joined room: ${articleId}`);
    });

    // Comments
    socket.on(DELETE_COMMENT_EVENT, (commentId: string, articleId: string) => {
      log(`Comment deleted: ${commentId} for article: ${articleId}`);
      io.to(articleId).emit(DELETE_COMMENT_EVENT, commentId);
    });

    socket.on(ADD_COMMENT_EVENT, (comment: Comment) => {
      log(`Comment added: ${comment.id} for article: ${comment.articleId}`);
      io.to(comment.articleId).emit(ADD_COMMENT_EVENT, comment);
    });

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