// app.js
require('dotenv').config();

// Enforce presence of JWT_SECRET
if (!process.env.JWT_SECRET) {
  console.error('Error: JWT_SECRET is not defined in environment.');
  process.exit(1);
}

const express = require('express');

// Route modules
const usersRoutes = require('./routes/users');
const chargerRoutes = require('./routes/chargers');
const sessionsRoutes = require('./routes/charger_sessions');
const pushRoutes = require('./routes/push'); // ✅ ADICIONA ISTO

const app = express();

// Global middlewares
app.use(express.json());

// Public routes (no auth)
app.use('/api/users', usersRoutes);

// Protected routes
// ✅ NOTA: chargers/sessions/push já têm router.use(verifyToken) internamente
// portanto não precisas passar verifyToken aqui.
app.use('/api/chargers', chargerRoutes);
app.use('/api/charger_sessions', sessionsRoutes);
app.use('/api/push', pushRoutes); // ✅ ISTO resolve /api/push/vapid-public-key

// Health check opcional (bom para produção)
app.get('/api/health', (req, res) => {
  res.json({ success: true, ok: true });
});

// Error handler (catch-all)
app.use((err, req, res, next) => {
  console.error('Unhandled error:', err);
  res
    .status(err.status || 500)
    .json({
      success: false,
      message: err.message || 'Internal Server Error',
    });
});

module.exports = app;
