import { Server } from 'socket.io';

let io: Server | undefined;

export default function handler(req: any, res: any) {
  if (!res.socket.server.io) {
    io = new Server(res.socket.server, {
      path: '/api/pos-draft-socket',
      addTrailingSlash: false,
      cors: {
        origin: '*',
        methods: ['GET', 'POST'],
      },
    });
    res.socket.server.io = io;

    // مسودات لكل مستخدم (ممكن لاحقاً ربطها بقاعدة بيانات)
    const drafts: Record<string, any> = {};

    io.on('connection', (socket) => {
      let userId = '';
      socket.on('auth', (data) => {
        userId = String(data?.userId || '');
        if (userId && drafts[userId]) {
          socket.emit('draft:init', drafts[userId]);
        }
      });

      socket.on('draft:diff', (diff) => {
        if (!userId) return;
        // diff: {op, path, value}
        if (!drafts[userId]) drafts[userId] = {};
        // مثال بسيط: فقط set (يمكن تطويره لاحقاً)
        if (diff.op === 'set') {
          drafts[userId][diff.path] = diff.value;
        } else if (diff.op === 'remove') {
          delete drafts[userId][diff.path];
        }
        io.to(socket.id).emit('draft:ack', diff);
      });

      socket.on('draft:clear', () => {
        if (userId) drafts[userId] = {};
      });
    });
  }
  res.end();
}

export const config = {
  api: {
    bodyParser: false,
  },
};
