require('dotenv').config();
const express = require('express');
const cors = require('cors');
const path = require('path');

const generateRoutes = require('./api/generate');
const cacheRoutes = require('./api/cache');

const app = express();

// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static('public'));

// Routes
app.use('/api/generate', generateRoutes);
app.use('/api/cache', cacheRoutes);

// Health check
app.get('/health', (req, res) => {
  res.json({
    status: 'ok',
    service: 'CompareKit',
    version: '1.0.0'
  });
});

// Serve frontend
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, '../public/index.html'));
});

// 404 handler
app.use((req, res) => {
  res.status(404).json({
    error: 'Not found'
  });
});

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

// Only start server if not running under Passenger
// Passenger manages the port and process
if (typeof(PhusionPassenger) === 'undefined') {
  const PORT = process.env.PORT || 3000;
  app.listen(PORT, () => {
    console.log('CompareKit Server running on port ' + PORT);
  });
}

// Export for Passenger
module.exports = app;
