const express = require('express');
const MySQLDB = require('./mysqldb');

const app = express();
const port = 4000;

app.use(express.json()); // Middleware to parse JSON

// Initialize MySQL database connection
const mySQLDB = new MySQLDB();

async function initializeDatabases() {
  try {
    await mySQLDB.createConnection();
  } catch (error) {
    console.error('Failed to initialize databases:', error);
    process.exit(1);
  }
}

app.get('/Pic', async (req, res) => {
  const mangaId = req.params.id;

  try {
    const sqlQuery = `SELECT * FROM manga_table WHERE manga_id = ${mySQLDB.connection.escape(mangaId)}`;
    const mySQLResults = await mySQLDB.query(sqlQuery);

    res.json({ mySQLResults });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.post('/insert', async (req, res) => {
  const { mangaId, mangaName } = req.body;
  console.log(mangaId, mangaName);
});

// Start server after initializing databases
initializeDatabases().then(() => {
  app.listen(port, () => {
    console.log(`API server listening at http://localhost:${port}`);
  });
});

