const fs = require('fs');
const path = require('path');

const saveLocation = async (req, res) => {
    try {
        const data = req.body;
        console.log("🔍 [DEBUG SERVER] Full Request Body:", JSON.stringify(data, null, 2)); // Debug payload structure
        const logFile = path.join(__dirname, '../logs/coordenadas.txt');
        
        // Ensure logs directory exists
        const logDir = path.dirname(logFile);
        if (!fs.existsSync(logDir)) {
            fs.mkdirSync(logDir, { recursive: true });
        }

        // Helper function to process a single location object
        const processSingleLocation = (locationData) => {
            const timestamp = new Date().toISOString().replace('T', ' ').slice(0, 19);
            const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress || 'unknown';

            // Intentar obtener alias desde "extras.alias" o "alias"
            let alias = 'Desconocido';
            if (locationData.extras && locationData.extras.alias) {
                alias = locationData.extras.alias;
            } else if (locationData.alias) {
                alias = locationData.alias;
            }

            let lat, lng;
            if (locationData.location && locationData.location.coords) {
                lat = locationData.location.coords.latitude;
                lng = locationData.location.coords.longitude;
            } else if (locationData.coords) {
                lat = locationData.coords.latitude;
                lng = locationData.coords.longitude;
            } else if (locationData.latitude && locationData.longitude) {
                lat = locationData.latitude;
                lng = locationData.longitude;
            }

            if (lat !== undefined && lng !== undefined) {
                console.log(`📍 [Server] Received: Alias=${alias} | Lat=${lat} | Lng=${lng}`);
                const linea = `[${timestamp}] Alias: ${alias} | IP: ${ip} | Lat: ${lat} | Lng: ${lng}\n`;
                fs.appendFileSync(logFile, linea);
                return true;
            } else {
                const errorLine = `[${timestamp}] Alias: ${alias} | IP: ${ip} | ⚠️ Formato inválido o sin coordenadas\n`;
                try {
                    fs.appendFileSync(logFile, errorLine);
                } catch (e) {
                    console.error("Error writing error log:", e);
                }
                return false;
            }
        };

        // Determine if it's a Batch (Array) or Single Location
        let locations = [];
        let globalAlias = null;

        // 1. Priority: JWT User (Secure & Reliable)
        if (req.user) {
             console.log("🔐 [Server] req.user payload:", JSON.stringify(req.user)); // Debug token content
             if (req.user.dni) {
                globalAlias = req.user.dni;
                console.log(`🔒 [Server] Authenticated User (GlobalAlias): ${globalAlias}`);
             }
        }

        // Case 1: Root Array
        if (Array.isArray(data)) {
            locations = data;
        } 
        // Case 2: Wrapped in "location" property (common with params)
        else if (data.location && Array.isArray(data.location)) {
            locations = data.location;
            // Check for alias in root (Fallback if no token)
            if (!globalAlias) {
                if (data.alias) globalAlias = data.alias;
                else if (data.params && data.params.alias) globalAlias = data.params.alias;
            }
        }
        // Case 3: Single Object
        else {
            locations = [data];
        }

        console.log(`📦 [Server] Processing ${locations.length} locations`);

        let savedCount = 0;
        locations.forEach(loc => {
            // FORCE Inject global alias (Security: Always trust Token over Client Body)
            if (globalAlias) {
                if (!loc.extras) loc.extras = {};
                loc.extras.alias = globalAlias; 
                // Also purge root alias to avoid confusion in processSingleLocation logic
                if (loc.alias) delete loc.alias; 
            }
            // Fallback for processSingleLocation helper logic...
            
            if (processSingleLocation(loc)) savedCount++;
        });

        if (savedCount > 0) {
            return res.json({ success: true, count: savedCount, message: "Locations saved" });
        } else {
             return res.json({ success: false, error: 'no_coords', message: "No valid coordinates found in batch/object" });
        }

    } catch (error) {
        console.error("Error saving location:", error);
        return res.status(500).json({ success: false, error: error.message });
    }
};

module.exports = {
    saveLocation
};
