const { Server } = require('socket.io');
const env = require('./env');

let io;

const initSocket = (httpServer) => {
  io = new Server(httpServer, {
    cors: {
      origin: env.allowedOrigins === '*' ? '*' : env.allowedOrigins.split(','),
      methods: ['GET', 'POST']
    }
  });

  io.on('connection', (socket) => {
    console.log(`[socket] istemci baglandi: ${socket.id}`);
    socket.emit('connection:ack', { message: 'Bookibra soket servisine hos geldiniz.' });
    socket.on('disconnect', () => {
      console.log(`[socket] istemci ayrildi: ${socket.id}`);
    });
  });

  return io;
};

const getIO = () => {
  if (!io) {
    throw new Error('Socket.IO baslatilmadi');
  }
  return io;
};

module.exports = { initSocket, getIO };
