const express = require('express');
const mysql = require('mysql2');
const cors = require('cors');
const bodyParser = require('body-parser');
require('dotenv').config();

const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(express.static(__dirname)); // Serve static files from current directory

// MySQL Connection
let db;
function handleDisconnect() {
    const connectionString = process.env.DATABASE_URL || process.env.MYSQL_URL || process.env.MYSQL_PRIVATE_URL;
    db = connectionString
        ? mysql.createConnection(connectionString)
        : mysql.createConnection({
            host: process.env.DB_HOST || 'localhost',
            user: process.env.DB_USER || 'root',
            password: process.env.DB_PASSWORD || '',
            database: process.env.DB_NAME || 'webgis_app',
            port: process.env.DB_PORT || 3306
        });

    db.connect(err => {
        if (err) {
            console.error('MySQL connection failed: ' + err.stack);
            setTimeout(handleDisconnect, 2000);
        } else {
            console.log('MySQL Connected...');
        }
    });

    db.on('error', err => {
        console.error('Database error:', err);
        if (err.code === 'PROTOCOL_CONNECTION_LOST') {
            handleDisconnect();
        } else {
            throw err;
        }
    });
}
handleDisconnect();

// Route to save a Road
app.post('/api/roads', (req, res) => {
    const { name, road_type, distance_meters, coordinates } = req.body;
    const query = 'INSERT INTO roads (name, road_type, distance_meters, coordinates) VALUES (?, ?, ?, ?)';
    
    db.query(query, [name, road_type, distance_meters, JSON.stringify(coordinates)], (err, result) => {
        if (err) return res.status(500).send(err);
        res.status(200).send({ message: 'Road saved successfully!', id: result.insertId });
    });
});

// Route to get all Roads
app.get('/api/roads', (req, res) => {
    const query = 'SELECT * FROM roads';
    
    db.query(query, (err, results) => {
        if (err) return res.status(500).send(err);
        res.status(200).send(results);
    });
});

// Route to save Land
app.post('/api/lands', (req, res) => {
    const { name, ownership_status, area_sq_meters, coordinates } = req.body;
    const query = 'INSERT INTO lands (name, ownership_status, area_sq_meters, coordinates) VALUES (?, ?, ?, ?)';
    
    db.query(query, [name, ownership_status, area_sq_meters, JSON.stringify(coordinates)], (err, result) => {
        if (err) return res.status(500).send(err);
        res.status(200).send({ message: 'Land saved successfully!', id: result.insertId });
    });
});

// Route to get all Lands
app.get('/api/lands', (req, res) => {
    const query = 'SELECT * FROM lands';
    
    db.query(query, (err, results) => {
        if (err) return res.status(500).send(err);
        res.status(200).send(results);
    });
});

// Route to update a Road
app.put('/api/roads/:id', (req, res) => {
    const { id } = req.params;
    const { name, road_type, distance_meters, coordinates } = req.body;
    const query = 'UPDATE roads SET name = ?, road_type = ?, distance_meters = ?, coordinates = ? WHERE id = ?';
    
    db.query(query, [name, road_type, distance_meters, JSON.stringify(coordinates), id], (err, result) => {
        if (err) return res.status(500).send(err);
        res.status(200).send({ message: 'Road updated successfully!' });
    });
});

// Route to delete a Road
app.delete('/api/roads/:id', (req, res) => {
    const { id } = req.params;
    const query = 'DELETE FROM roads WHERE id = ?';
    
    db.query(query, [id], (err, result) => {
        if (err) return res.status(500).send(err);
        res.status(200).send({ message: 'Road deleted successfully!' });
    });
});

// Route to update a Land
app.put('/api/lands/:id', (req, res) => {
    const { id } = req.params;
    const { name, ownership_status, area_sq_meters, coordinates } = req.body;
    const query = 'UPDATE lands SET name = ?, ownership_status = ?, area_sq_meters = ?, coordinates = ? WHERE id = ?';
    
    db.query(query, [name, ownership_status, area_sq_meters, JSON.stringify(coordinates), id], (err, result) => {
        if (err) return res.status(500).send(err);
        res.status(200).send({ message: 'Land updated successfully!' });
    });
});

// Route to delete a Land
app.delete('/api/lands/:id', (req, res) => {
    const { id } = req.params;
    const query = 'DELETE FROM lands WHERE id = ?';
    
    db.query(query, [id], (err, result) => {
        if (err) return res.status(500).send(err);
        res.status(200).send({ message: 'Land deleted successfully!' });
    });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
});