const mariadb = require('mariadb');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');

app.use(bodyParser.json());
const serverPort = 3000;

const databaseCredentials = {
    host: '127.0.0.1',
    user: 'fitbot',
    password: 'fitbot123',
    database: 'fitbot',
    connectionLimit: 5,
    allowUnauthorized: true
};

// Create connection pool
const pool = mariadb.createPool(databaseCredentials);

// Register incoming HTTP request handlers
require('./incoming_request_handlers')(app, pool);

let ipAddress = ''; // to store the received IP address

// endpoint to receive an IP address from an external source
app.post('/set-ip', (req, res) => {
    ipAddress = req.body.ip;
    console.log('IP address received:', ipAddress);
});

// endpoint for the ESP32 to fetch the IP address
app.get('/get-ip', (req, res) => {
    res.json({ ip: ipAddress });
    console.log('IP address sent to ESP32');
});

// Start server
app.listen(serverPort, () => {
    console.log(`Server running on port ${serverPort}`);
});