const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { authenticateToken } = require('../middleware/auth');

// Get last location for a device
router.get('/:deviceId/last', authenticateToken, async (req, res) => {
  try {
    const { deviceId } = req.params;
    
    const query = `
      SELECT latitude, longitude, altitude, accuracy, speed, heading, address, timestamp
      FROM device_locations 
      WHERE device_id = ? 
      ORDER BY timestamp DESC 
      LIMIT 1
    `;
    
    const [rows] = await db.execute(query, [deviceId]);
    
    if (rows.length === 0) {
      return res.status(404).json({ message: 'No location data found for this device' });
    }
    
    res.json(rows[0]);
  } catch (error) {
    console.error('Error fetching location:', error);
    res.status(500).json({ message: 'Server error' });
  }
});

// Get location history for a device
router.get('/:deviceId/history', authenticateToken, async (req, res) => {
  try {
    const { deviceId } = req.params;
    const { start, end } = req.query;
    
    const query = `
      SELECT latitude, longitude, altitude, accuracy, speed, heading, address, timestamp
      FROM device_locations 
      WHERE device_id = ? AND timestamp BETWEEN ? AND ?
      ORDER BY timestamp ASC
    `;
    
    const [rows] = await db.execute(query, [deviceId, start, end]);
    
    res.json(rows);
  } catch (error) {
    console.error('Error fetching location history:', error);
    res.status(500).json({ message: 'Server error' });
  }
});

router.post('/:deviceId', authenticateToken, async (req, res) => {
  try {
    const { deviceId } = req.params;
    const {
      latitude,
      longitude,
      altitude = null,
      accuracy = null,
      speed = null,
      battery_level = null,
      address = null,
      timestamp = null
    } = req.body || {};

    if (!deviceId || latitude === undefined || longitude === undefined) {
      return res.status(400).json({ message: 'deviceId, latitude and longitude are required' });
    }

    const insertQuery = `
      INSERT INTO device_locations
        (device_id, latitude, longitude, altitude, accuracy, speed, battery_level, address, timestamp, created_at)
      VALUES
        (?, ?, ?, ?, ?, ?, ?, ?, COALESCE(?, NOW()), NOW())
    `;

    await db.execute(insertQuery, [
      deviceId,
      latitude,
      longitude,
      altitude,
      accuracy,
      speed,
      battery_level,
      address,
      timestamp
    ]);

    return res.json({ message: 'success' });
  } catch (error) {
    console.error('Error inserting device location:', error);
    return res.status(500).json({ message: 'Server error' });
  }
});

module.exports = router;