// ==============================================================================
// Void-Genesis - Lobby Backend Server (Einstiegspunkt)
// ==============================================================================

import express from 'express';
import cors from 'cors';
import pool from './db.js';

import authRoutes from './routes/auth.routes.js';
import sectorRoutes from './routes/sector.routes.js';
import { pingSectors } from './services/heartbeat.service.js';
import { initLobbyCronJobs } from './services/cron.service.js';

const app = express();
const PORT = process.env.PORT || 3000;

// Middleware
app.use(cors());
app.use(express.json());

app.use('/api/auth', authRoutes);
app.use('/api/sectors', sectorRoutes);

// Unsere bestehende Health-Route
app.get('/api/health', (req, res) => {
  res.json({ 
    status: 'ok', 
    message: 'Void-Genesis Lobby Backend läuft!',
    timestamp: new Date().toISOString()
  });
});

// Eine Test-Route für die Datenbank
app.get('/api/db-test', async (req, res) => {
  try {
    const result = await pool.query('SELECT NOW()');
    
    res.json({
      status: 'success',
      message: 'Datenbankverbindung steht!',
      db_time: result.rows[0].now
    });
  } catch (err) {
    console.error('Fehler bei der DB-Abfrage:', err);
    res.status(500).json({ 
      status: 'error', 
      message: 'Datenbankfehler',
      error: err.message 
    });
  }
});


// Server starten
app.listen(PORT, () => {
  console.log(`🚀 Void-Genesis Lobby Backend gestartet auf Port ${PORT}`);
  console.log(`Environment: ${process.env.NODE_ENV}`);
  initLobbyCronJobs();
  console.log('💓 Heartbeat-System initialisiert (Intervall: 30s)');
  pingSectors();
  setInterval(pingSectors, 30000);
});

