const authRoutes = require('./authRoutes');
const app = require('./app');
const db = require('./db');

// Routes
app.use(authRoutes); // Use the auth routes

// Create new session
app.post('/api/session', async (req, res) => {
  const sessionId = req.body.sessionId;
  const query = 'INSERT INTO sessions (id) VALUES (?)';
  await db.query(query, [sessionId], (err, result) => {
    if (err) return res.status(500).json({ error: err });
    res.status(200).json({ sessionId });
  });
});

// Add user to session
app.post('/api/session/:sessionId/user', async (req, res) => {
  const { sessionId } = req.params;
  const { userId, provider } = req.body;

  // Insert the user into the `users` table if they don't already exist
  const userQuery = `
    INSERT INTO users (id, provider)
    VALUES (?, ?)
    ON DUPLICATE KEY UPDATE id = id`; // If the user already exists, do nothing

  // Insert the user into the `session_users` table for this session
  const sessionUserQuery = `
    INSERT INTO session_users (session_id, user_id, provider)
    VALUES (?, ?, ?)
    ON DUPLICATE KEY UPDATE session_id = session_id`; // If the user is already in the session, do nothing

  // Insert the initial vote (-1) for the user in this session
  const voteQuery = `
    INSERT INTO votes (session_id, user_id, vote)
    VALUES (?, ?, -1)
    ON DUPLICATE KEY UPDATE vote = -1`; // If a vote already exists, reset it to -1

  try {
    // Insert the user into the `users` table
    await db.query(userQuery, [userId, provider]);

    // Add the user to the `session_users` table
    await db.query(sessionUserQuery, [sessionId, userId, provider]);

    // Set the initial vote for the user in the session
    await db.query(voteQuery, [sessionId, userId]);

    res.status(200).json({ userId });
  } catch (err) {
    console.error('Error adding user to session:', err);
    res.status(500).json({ error: 'Server error' });
  }
});

// Get users in a session
app.get('/api/session/:sessionId/users', async (req, res) => {
  const { sessionId } = req.params;
  const query = `
    SELECT users.id, users.username
    FROM votes
    JOIN users ON votes.user_id = users.id
    WHERE session_id = ?
  `;

  try {
    const [results] = await db.query(query, [sessionId]);
    console.log('Query results:', results); // Log query result
    res.status(200).json(results);
  } catch (err) {
    console.error('Error fetching session users:', err);
    res.status(500).json({ error: 'Server error' });
  }
});

app.delete('/api/session/:sessionId/votes/:userId', async (req, res) => {
  const { sessionId, userId } = req.params;
  const query = 'DELETE FROM votes WHERE session_id = ? AND user_id = ?';

  try {
    const [result] = await db.query(query, [sessionId, userId]);
    res
      .status(200)
      .json({ success: true, message: 'Vote removed successfully' });
  } catch (error) {
    console.error('Error removing vote:', error);
    res.status(500).json({ error: 'Server error' });
  }
});

app.delete('/api/session/:sessionId/users/:userId', async (req, res) => {
  const { sessionId, userId } = req.params;
  const query =
    'DELETE FROM session_users WHERE session_id = ? AND user_id = ?';

  try {
    const [result] = await db.query(query, [sessionId, userId]);
    res
      .status(200)
      .json({ success: true, message: 'User removed successfully' });
  } catch (error) {
    console.error('Error removing user:', error);
    res.status(500).json({ error: 'Server error' });
  }
});

// Start the server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
