const express = require('express');
const databaseService = require('./src/services/database.service');

// Configuration
const PORT = process.env.PORT || 4000;

// Initialize Express app
const app = express();
app.use(express.json());

async function initializeDatabases() {
  try {
    await databaseService.createConnection();
  } catch (error) {
    process.exit(1);
  }
}

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

  try {
    const sqlQuery = 'SELECT * FROM mangas WHERE mangaId = ?';
    const mySQLResults = await databaseService.query(sqlQuery, [mangaId]);

    if (!mySQLResults || mySQLResults.length === 0) {
      return res.status(404).json({ error: 'Manga not found' });
    }

    res.json({ data: mySQLResults[0] });
  } catch (error) {
    console.error('Error fetching manga:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

app.get('/getMangaId/:mangaName', async (req, res) => {
  const mangaName = req.params.mangaName;

  try {
    const sqlQuery = 'SELECT mangaId FROM mangas WHERE mangaName = ?';
    const mySQLResults = await databaseService.query(sqlQuery, [mangaName]);

    if (!mySQLResults || mySQLResults.length === 0) {
      return res.status(404).json({ error: 'Manga not found' });
    }

    res.json({ data: mySQLResults[0] });
  } catch (error) {
    console.error('Error getting manga ID:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

app.get('/getGenres/:genre', async (req, res) => {
  const genre = req.params.genre;

  try {
    const sqlQuery = 'SELECT genreId FROM genres WHERE genreName = ?';
    const mySQLResults = await databaseService.query(sqlQuery, [genre]);

    if (!mySQLResults || mySQLResults.length === 0) {
      return res.status(404).json({ error: 'Genre not found' });
    }

    res.json({ data: mySQLResults[0] });
  } catch (error) {
    console.error('Error getting genre:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

app.post('/insertGenre', async (req, res) => {
  const genre = req.body;

  try {
    const sqlQuery = 'INSERT INTO genres (genreName) VALUES (?)';
    const mySQLResults = await databaseService.query(sqlQuery, [genre.genreName]);
    res.json({ 
      success: true, 
      message: 'Genre inserted successfully',
      genreId: mySQLResults.insertId
    });
  } catch (error) {
    console.error('Error inserting genre:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

app.post('/insertMangaGenres', async (req, res) => {
  const genres = req.body;

  try {
    const sqlQuery = `
      INSERT INTO manga_genres (
        mangaId,
        genreId
      ) VALUES (?, ?)
    `;

    const params = [
      genres.mangaId,
      genres.genreId
    ];

    await databaseService.query(sqlQuery, params);
    res.json({ 
      success: true, 
      message: 'Manga genres inserted successfully',
    });
  } catch (error) {
    console.error('Error inserting manga genres:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

app.post('/insertMangaChapter', async (req, res) => {
  const chapterInfo = req.body;

  try {
    const sqlQuery = `
      INSERT INTO chapters (
        mangaId,
        chapterOrder,
        chapterName
      ) VALUES (?, ?, ?)
    `;

    const params = [
      chapterInfo.mangaId,
      chapterInfo.chapterOrder,
      chapterInfo.chapterName
    ];

    await databaseService.query(sqlQuery, params);
    res.json({ 
      success: true, 
      message: 'Chapter inserted successfully',
    });
  } catch (error) {
    console.error('Error inserting chapter:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

app.post('/insertMangaInfo', async (req, res) => {
  const mangaInfo = req.body;

  try {
    const sqlQuery = `
      INSERT INTO mangas (
        mangaId,
        mangaName,
        mangaAuthor,
        mangaNickname,
        mangaStatus
      ) VALUES (?, ?, ?, ?, ?)
      ON DUPLICATE KEY UPDATE
        mangaName = VALUES(mangaName),
        mangaAuthor = VALUES(mangaAuthor),
        mangaNickname = VALUES(mangaNickname),
        mangaStatus = VALUES(mangaStatus)
    `;

    const params = [
      mangaInfo.mangaId,
      mangaInfo.name,
      mangaInfo.author,
      JSON.stringify(mangaInfo.nickNames),
      mangaInfo.status
    ];

    await databaseService.query(sqlQuery, params);
    res.json({ 
      success: true, 
      message: 'Manga details inserted successfully',
    });
  } catch (error) {
    console.error('Error inserting manga details:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error('Unhandled error:', err);
  res.status(500).json({ error: 'Internal server error' });
});

// Start server
initializeDatabases()
  .then(() => {
    app.listen(PORT, () => {
      console.log(`API server listening at http://localhost:${PORT}`);
    });
  })
  .catch(error => {
    console.error('Failed to start server:', error);
    process.exit(1);
  });

