import { Router } from 'express';
import { ManualPortConfig } from '../../services/manualPortConfig.js';
import { serverLogger } from '../../../utils/serverLogger.js';
/**
 * Manual Port Configuration Routes
 *
 * Allows users to manually configure their public IP and port
 * when automatic port forwarding fails.
 */ export function createManualPortRoutes() {
    const router = Router();
    const manualPortConfig = new ManualPortConfig();
    /**
   * GET /api/manual-port/config
   * Get current manual port configuration
   */ router.get('/config', async (req, res)=>{
        try {
            await manualPortConfig.load();
            const config = manualPortConfig.getConfig();
            res.json({
                success: true,
                config
            });
        } catch (error) {
            serverLogger.error('[ManualPort API] Failed to get config:', error);
            res.status(500).json({
                success: false,
                error: 'Failed to get configuration'
            });
        }
    });
    /**
   * POST /api/manual-port/config
   * Save manual port configuration
   */ router.post('/config', async (req, res)=>{
        try {
            const { enabled, publicIP, publicPort, localPort } = req.body;
            // Validate input
            if (enabled && !publicIP) {
                return res.status(400).json({
                    success: false,
                    error: 'Public IP is required when enabling manual configuration'
                });
            }
            // Validate IP format if provided
            if (publicIP) {
                const ipRegex = /^(\d{1,3}\.){3}\d{1,3}$/;
                if (!ipRegex.test(publicIP)) {
                    return res.status(400).json({
                        success: false,
                        error: 'Invalid IP address format'
                    });
                }
            }
            // Validate port numbers
            const portNum = publicPort || 51823;
            const localPortNum = localPort || 51823;
            if (portNum < 1 || portNum > 65535 || localPortNum < 1 || localPortNum > 65535) {
                return res.status(400).json({
                    success: false,
                    error: 'Port must be between 1 and 65535'
                });
            }
            // Save configuration
            await manualPortConfig.save({
                enabled: !!enabled,
                publicIP,
                publicPort: portNum,
                localPort: localPortNum
            });
            serverLogger.info('[ManualPort API] Configuration saved:', {
                enabled,
                publicIP,
                publicPort: portNum
            });
            res.json({
                success: true,
                message: 'Configuration saved successfully'
            });
        } catch (error) {
            serverLogger.error('[ManualPort API] Failed to save config:', error);
            res.status(500).json({
                success: false,
                error: 'Failed to save configuration'
            });
        }
    });
    /**
   * DELETE /api/manual-port/config
   * Clear manual port configuration
   */ router.delete('/config', async (req, res)=>{
        try {
            await manualPortConfig.save({
                enabled: false,
                localPort: 51823
            });
            serverLogger.info('[ManualPort API] Configuration cleared');
            res.json({
                success: true,
                message: 'Configuration cleared'
            });
        } catch (error) {
            serverLogger.error('[ManualPort API] Failed to clear config:', error);
            res.status(500).json({
                success: false,
                error: 'Failed to clear configuration'
            });
        }
    });
    /**
   * POST /api/manual-port/test
   * Test manual port configuration
   */ router.post('/test', async (req, res)=>{
        try {
            await manualPortConfig.load();
            if (!manualPortConfig.isConfigured()) {
                return res.status(400).json({
                    success: false,
                    error: 'No manual configuration found'
                });
            }
            // Test the connection
            const isWorking = await manualPortConfig.testConnection();
            res.json({
                success: isWorking,
                message: isWorking ? 'Connection test successful' : 'Connection test failed - check your port forwarding settings'
            });
        } catch (error) {
            serverLogger.error('[ManualPort API] Test failed:', error);
            res.status(500).json({
                success: false,
                error: 'Connection test failed'
            });
        }
    });
    /**
   * GET /api/manual-port/instructions
   * Get setup instructions for manual port forwarding
   */ router.get('/instructions', async (req, res)=>{
        try {
            // Detect if Google WiFi is present
            const os = await import('os');
            const interfaces = os.networkInterfaces();
            let isGoogleWifi = false;
            for (const [name, ifaces] of Object.entries(interfaces)){
                if (!ifaces) continue;
                for (const iface of ifaces){
                    if (iface.family === 'IPv4' && !iface.internal && iface.address.startsWith('192.168.86.')) {
                        isGoogleWifi = true;
                        break;
                    }
                }
            }
            const instructions = [];
            if (isGoogleWifi) {
                instructions.push({
                    title: 'Google WiFi Detected',
                    steps: [
                        'Open the Google Home app on your phone',
                        'Tap your WiFi network',
                        'Tap Settings → Advanced networking → Port management',
                        'Tap "+" to add a new rule',
                        'Select your Mac Mini from the device list',
                        'Set internal port: 51823',
                        'Set external port: 51823',
                        'Select TCP & UDP',
                        'Save the rule'
                    ]
                });
                instructions.push({
                    title: 'If you have another router (double NAT)',
                    steps: [
                        'Access your main router\'s admin panel',
                        'Find the port forwarding section',
                        'Add a rule to forward port 51823 to 192.168.86.1 (Google WiFi router)',
                        'Save and apply changes'
                    ]
                });
            } else {
                instructions.push({
                    title: 'Standard Router Port Forwarding',
                    steps: [
                        'Access your router\'s admin panel (usually 192.168.1.1 or 192.168.0.1)',
                        'Find the port forwarding or virtual server section',
                        'Add a new rule:',
                        '  - Device/Internal IP: Your Mac\'s IP address',
                        '  - Internal Port: 51823',
                        '  - External Port: 51823',
                        '  - Protocol: TCP/UDP or Both',
                        'Save and apply the changes'
                    ]
                });
            }
            instructions.push({
                title: 'Find Your Public IP',
                steps: [
                    'Visit https://whatismyipaddress.com',
                    'Copy your IPv4 address',
                    'Enter it in the Public IP field above'
                ]
            });
            res.json({
                success: true,
                isGoogleWifi,
                instructions
            });
        } catch (error) {
            serverLogger.error('[ManualPort API] Failed to get instructions:', error);
            res.status(500).json({
                success: false,
                error: 'Failed to generate instructions'
            });
        }
    });
    return router;
}
export default createManualPortRoutes;

//# sourceMappingURL=manualPortRoutes.js.map