import { Server, Socket } from 'socket.io';
import http from 'http';
import jwt from 'jsonwebtoken';

let io: Server | null = null;

export const initSocket = (server: http.Server, origins: string[]) => {
  io = new Server(server, {
    cors: {
      origin: (origin, callback) => {
        if (!origin || origins.includes(origin)) {
          return callback(null, true);
        }
        return callback(new Error('Socket.io CORS origin not allowed'), false);
      },
      credentials: true,
    },
  });

  io.use((socket: Socket, next) => {
    try {
      const token = socket.handshake.auth?.token as string | undefined;
      if (!token) return next();

      const secret = process.env.JWT_SECRET || 'your-secret-key-change-in-production';
      const decoded = jwt.verify(token, secret) as { userId: string; role: string };
      (socket as any).userId = decoded.userId;
      (socket as any).role = decoded.role;
      socket.join(`user:${decoded.userId}`);
      next();
    } catch (err: any) {
      console.error('Socket auth error:', err?.message || err);
      // Surface an authentication error to the client while still preventing a crash
      next(new Error('server error'));
    }
  });

  io.on('connection', (socket: Socket) => {
    // Optionally, add logging or heartbeats here
    socket.on('disconnect', () => {
      // Clean up if needed
    });
  });

  return io;
};

export const getIo = () => io;

