const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    }
});

const PORT = 3001;

// Основной HTTP endpoint
app.get('/', (req, res) => {
    res.send('GodEye Test Server Running');
});

// Socket.IO обработчики
io.on('connection', (socket) => {
    console.log('📱 Android device connected:', socket.id);

    socket.on('register:android', (data) => {
        console.log('📋 Device registration:', data);
        socket.emit('register:success', {
            message: 'Device registered successfully',
            deviceId: data.deviceId
        });
    });

    socket.on('camera:response', (data) => {
        console.log('📷 Camera response:', data);
    });

    socket.on('webrtc:answer', (data) => {
        console.log('🔗 WebRTC answer:', data);
    });

    socket.on('webrtc:ice-candidate', (data) => {
        console.log('🧊 ICE candidate:', data);
    });

    socket.on('disconnect', () => {
        console.log('❌ Device disconnected:', socket.id);
    });

    // Тестовый запрос камеры через 5 секунд после подключения
    setTimeout(() => {
        socket.emit('camera:request', {
            sessionId: 'test-session-123',
            operatorId: 'test-operator',
            cameraType: 'back'
        });
        console.log('📹 Sent test camera request to device');
    }, 5000);
});

server.listen(PORT, '0.0.0.0', () => {
    console.log(`🚀 GodEye Test Server running on port ${PORT}`);
    console.log(`📡 Socket.IO server ready for connections`);
    console.log(`🌐 Server accessible at: http://0.0.0.0:${PORT}`);
});
