import { Namespace, Socket } from "socket.io";
import { requireAuth } from "../../pkg/middleware/authMiddleware.js";

export const setupAllLogs = (io: Namespace) => {
    // Wrap middleware for Socket.IO
    io.use(async (socket: Socket, next) => {
        try {
            // Mock Express req/res object
            const req = socket.request as any;

            // Create a mini next function that throws an error if unauthorized
            await new Promise<void>((resolve, reject) => {
                const fakeRes: any = {
                    status: () => ({
                        json: (obj: any) => reject(new Error(obj.error)),
                    }),
                };
                const nextFn = (err?: any) => (err ? reject(err) : resolve());

                // Call your middleware
                requireAuth("", ["systemAdmin", "admin"])(req, fakeRes, nextFn);
            });

            // Auth passed
            next();
        } catch (err: any) {
            next(new Error(err.message || "Unauthorized"));
        }
    });

    io.on("connection", (socket: Socket) => {
        console.log(
            "✅ Authenticated client connected to channel2:",
            socket.id
        );

        socket.on("ping", () => socket.emit("pong"));

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