const express = require('express');
const crypto = require('crypto');
const { getPool } = require('../config/database'); // Sửa đường dẫn này

const router = express.Router();

// ---- Routes ----

// Check Key
router.post('/check-key', async (req, res) => {
    const { serverKey } = req.body;
    if (!serverKey) return res.status(400).json({ success: false, error: 'Server key required' });

    try {
        const pool = getPool();
        const [rows] = await pool.execute(
            'SELECT * FROM ticket_active WHERE key_hash = ? AND enabled = 1',
            [serverKey]
        );
        
        if (rows.length === 0) {
            return res.status(401).json({ success: false, error: 'Sai key!' });
        }

        res.json({
            success: true,
            message: 'Key hợp lệ',
            serverInfo: { name: rows[0].server_name, maxClients: rows[0].max_clients }
        });
    } catch (error) {
        console.error('Database error:', error);
        res.status(500).json({ success: false, error: 'DB error' });
    }
});

// Save Server Info
// Save Server Info
// Save Server Info
// Save Server Info
router.post('/save-server-info', async (req, res) => {
    const { serverKey, serverInfo } = req.body;
    if (!serverKey) return res.status(400).json({ success: false, error: 'Server key required' });

    try {
        console.log('🔍 Starting save-server-info...');
        console.log('📝 Server key:', serverKey);
        console.log('📝 Server info:', JSON.stringify(serverInfo, null, 2));
        
        const pool = getPool();
        console.log('✅ Database pool obtained');
        
        // Check if key exists
        const [keyRows] = await pool.execute(
            'SELECT * FROM ticket_active WHERE key_hash = ? AND enabled = 1',
            [serverKey]
        );
        
        console.log('📊 Key rows found:', keyRows.length);
        
        if (keyRows.length === 0) {
            console.log('❌ Key not found or disabled');
            return res.status(401).json({ success: false, error: 'Sai key!' });
        }

        console.log('✅ Key validated, preparing to save server info');

        // Sửa key names để khớp với Python script
        const serverData = {
            key_hash: serverKey,
            server_ip: serverInfo?.server_ip || null,        // ✅ Đúng key name
            server_port: serverInfo?.server_port || null,    // ✅ Đúng key name
            server_version: serverInfo?.server_version || null, // ✅ Đúng key name
            player_count: serverInfo?.player_count || null,  // ✅ Đúng key name
            max_players: keyRows[0].max_clients,
            server_status: 'online',
            last_heartbeat: new Date()
        };
        
        console.log('🔧 Server data:', serverData);

        // Kiểm tra xem server info đã tồn tại chưa
        const [existingRows] = await pool.execute(
            'SELECT id FROM server_info WHERE key_hash = ?',
            [serverKey]
        );

        if (existingRows.length > 0) {
            // Update existing record
            console.log('🔄 Updating existing server info');
            await pool.execute(
                `UPDATE server_info SET 
                 server_ip = ?, 
                 server_port = ?, 
                 server_version = ?, 
                 player_count = ?, 
                 max_players = ?, 
                 server_status = ?, 
                 last_heartbeat = NOW()
                 WHERE key_hash = ?`,
                [
                    serverData.server_ip,
                    serverData.server_port,
                    serverData.server_version,
                    serverData.player_count,
                    serverData.max_players,
                    serverData.server_status,
                    serverKey
                ]
            );
        } else {
            // Insert new record
            console.log('➕ Inserting new server info');
            await pool.execute(
                `INSERT INTO server_info 
                 (key_hash, server_ip, server_port, server_version, player_count, max_players, server_status, last_heartbeat) 
                 VALUES (?, ?, ?, ?, ?, ?, ?, NOW())`,
                [
                    serverData.key_hash,
                    serverData.server_ip,
                    serverData.server_port,
                    serverData.server_version,
                    serverData.player_count,
                    serverData.max_players,
                    serverData.server_status
                ]
            );
        }

        console.log('✅ Server info saved successfully');
        res.json({ success: true, message: 'Lưu thành công' });
    } catch (error) {
        console.error('❌ Database error:', error);
        console.error('❌ Error stack:', error.stack);
        res.status(500).json({ success: false, error: 'Lưu thất bại: ' + error.message });
    }
});

// List servers
router.get('/servers', async (req, res) => {
    try {
        const pool = getPool();
        const [rows] = await pool.execute('SELECT * FROM server_info ORDER BY last_heartbeat DESC');
        res.json({ success: true, servers: rows });
    } catch (error) {
        console.error('Database error:', error);
        res.status(500).json({ success: false, error: 'DB error' });
    }
});

// Status
router.get('/status', (req, res) => {
    res.json({
        status: 'online',
        timestamp: Date.now(),
        version: '2.0',
        message: 'Custom FiveM Auth Server'
    });
});

module.exports = router;