require('dotenv').config();
const db = require('../config/database');

// Test data matching what frontend sends
const testData = {
    request_by: 4,
    is_urgent: 0,
    location: 'Current Location',
    destination: 'Lilongwe: Likuni',
    latitude: -13.9610416,
    longitude: 33.7940749,
    destination_latitude: -14.0281706,
    destination_longitude: 33.7066948,
    status: 'pending'
};

console.log('Test data:', testData);
console.log('destination_latitude type:', typeof testData.destination_latitude);
console.log('destination_longitude type:', typeof testData.destination_longitude);

const { request_by, is_urgent, location, destination, latitude, longitude, destination_latitude, destination_longitude, status } = testData;

// Convert to numbers
const destLat = parseFloat(destination_latitude);
const destLng = parseFloat(destination_longitude);

console.log('\nAfter parseFloat:');
console.log('destLat:', destLat, 'type:', typeof destLat);
console.log('destLng:', destLng, 'type:', typeof destLng);

const query = `INSERT INTO ambulance_requests 
    (request_by, is_urgent, location, destination, latitude, longitude, destination_latitude, destination_longitude, status) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`;

const params = [
    request_by, 
    is_urgent || false, 
    location, 
    destination || null, 
    latitude, 
    longitude,
    destLat,
    destLng,
    status || 'pending'
];

console.log('\nQuery parameters:');
params.forEach((param, index) => {
    console.log(`  [${index}]:`, param, `(type: ${typeof param})`);
});

db.query(query, params, (err, results) => {
    if (err) {
        console.error('Error:', err.message);
        console.error('Full error:', err);
    } else {
        console.log('\n✓ Insert successful! ID:', results.insertId);
        
        // Verify the insert
        db.query('SELECT id, latitude, longitude, destination_latitude, destination_longitude FROM ambulance_requests WHERE id = ?', [results.insertId], (err, rows) => {
            if (err) {
                console.error('Error fetching:', err);
            } else {
                console.log('\n✓ Verified inserted record:');
                console.log(JSON.stringify(rows[0], null, 2));
            }
            process.exit(0);
        });
    }
});







