const { v4: uuidv4 } = require('uuid'); // ✅ Generate unique session IDs
const Tracking = require('../models/Tracking');

// ✅ Store GPS Data with Session ID
exports.storeLocation = async (req, res) => {

 console.log("new session started",req.body);

    const { userId, deviceId, trackingSessionId, latitude, longitude } = req.body;

    if (!userId || !deviceId || !trackingSessionId || !latitude || !longitude) {
        return res.status(400).json({ message: 'Invalid data' });
    }

    try {
        let tracking = await Tracking.findOne({ userId, trackingSessionId });

        if (!tracking) {
            tracking = new Tracking({ userId, deviceId, trackingSessionId, locations: [] });
        }

        tracking.locations.push({ latitude, longitude });

        await tracking.save();
     //   console.log("data is",req.body);
        res.status(200).json({ message: 'Location saved', tracking });
    } catch (error) {
        console.error('❌ Error saving location:', error);
        res.status(500).json({ message: 'Error saving location' });
    }
};

// ✅ Start New Tracking Session
exports.startTrackingSession = async (req, res) => {
    const { userId, deviceId } = req.body;

    if (!userId || !deviceId) {
        return res.status(400).json({ message: 'Invalid data' });
    }



    const trackingSessionId = uuidv4(); // ✅ Generate a new session ID

console.log(" new id is genrating...")

    res.status(200).json({ message: 'New tracking session started', trackingSessionId });
};

// ✅ Retrieve All Tracking Sessions for a User
exports.getTrackingHistory2 = async (req, res) => {
    const { userId } = req.params;

    try {
        const trackingSessions = await Tracking.find({ userId });

        if (!trackingSessions.length) {
            return res.status(404).json({ message: 'No tracking data found' });
        }

        res.status(200).json({ trackingSessions });
    } catch (error) {
        console.error('❌ Error retrieving location history:', error);
        res.status(500).json({ message: 'Error retrieving location history' });
    }
};


exports.getTrackingHistory1 = async (req, res) => {
    const { userId } = req.params;

    try {
        const trackingSessions = await Tracking.find({ userId });

        if (!trackingSessions.length) {
            return res.status(404).json({ message: 'No tracking data found' });
        }

        // Extract start, end, and full path for each session
        const formattedSessions = trackingSessions.map(session => {
            if (session.locations.length >= 2) {
                return {
                    trackingSessionId: session.trackingSessionId,
                    startPoint: session.locations[0], // First recorded location
                    endPoint: session.locations[session.locations.length - 1], // Last recorded location
                    path: session.locations, // All points in order
                    totalLocations: session.locations.length
                };
            }
            return null; // Ignore sessions with less than 2 locations
        }).filter(session => session !== null);

        res.status(200).json({ trackingSessions: formattedSessions });
    } catch (error) {
        console.error('❌ Error retrieving location history:', error);
        res.status(500).json({ message: 'Error retrieving location history' });
    }
};
// ✅ Get List of Tracking Sessions with Usernames
exports.getTrackingSessions = async (req, res) => {
   



        const { startDate, endDate } = req.query;

        try {

            let query = {};
            if (startDate && endDate) {
                let start = new Date(startDate);
                start.setUTCHours(0, 0, 0, 0);
            
                let end = new Date(endDate);
                end.setUTCHours(23, 59, 59, 999); // Set end time to the end of the day
            
                query = {
                    createdAt: {
                        $gte: start,
                        $lte: end,
                    }
                };
            }
            
          const sessions = await Tracking.find(query).populate('userId', 'username'); // Fetch user name
     //   const sessions = await Tracking.find().populate('userId', 'username'); // Fetch user name

      //  console.log("tracking data....")
        if (!sessions.length) {
            return res.status(404).json({ message: 'No tracking sessions found' });
        }

        // Format response
        const formattedSessions = sessions.map(session => ({
         trackingSessionId: session.trackingSessionId,
        userId: session.userId._id, // User ID
        userName: session.userId.username, // User Name
        startTime: session.locations[0]?.timestamp || "N/A",
        endTime: session.locations[session.locations.length - 1]?.timestamp || "N/A"
      }));
console.log(formattedSessions);
        res.status(200).json({ sessions: formattedSessions });
    } catch (error) {
        console.error('❌ Error retrieving tracking sessions:', error);
        res.status(500).json({ message: 'Error retrieving tracking sessions' });
    }
};

// ✅ Get Tracking History for a Specific Session
exports.getTrackingHistory = async (req, res) => {
    const { userId, trackingSessionId } = req.params;

    try {
        const tracking = await Tracking.findOne({ userId, trackingSessionId });

        if (!tracking || tracking.locations.length < 2) {
            return res.status(404).json({ message: 'Not enough tracking data' });
        }

        res.status(200).json({
            trackingSessionId: tracking.trackingSessionId,
            startPoint: tracking.locations[0], // First location
            endPoint: tracking.locations[tracking.locations.length - 1], // Last location
            path: tracking.locations // Full path
        });
    } catch (error) {
        console.error('❌ Error retrieving tracking history:', error);
        res.status(500).json({ message: 'Error retrieving tracking history' });
    }
};


// ✅ Delete Tracking Session by Session ID
exports.deleteTrackingSession = async (req, res) => {
    const { trackingSessionId } = req.params;
console.log('trailing session', trackingSessionId);
    try {
        const result = await Tracking.deleteOne({ trackingSessionId });

        if (result.deletedCount === 0) {
            return res.status(404).json({ message: 'Tracking session not found' });
        }

        res.status(200).json({ message: 'Tracking session deleted successfully' });
    } catch (error) {

        console.error('❌ Error deleting tracking session:', error);
        res.status(500).json({ message: 'Error deleting tracking session' });
    }
};
