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

const { testConnection } = require('./utils/db');
const apiRoutes = require('./routes/api');

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

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

// Serve static files from public directory
app.use(express.static(path.join(__dirname, '..', 'public')));

// API routes
app.use('/api', apiRoutes);

// Health check endpoint
app.get('/health', async (req, res) => {
  const dbConnected = await testConnection();
  res.json({
    status: dbConnected ? 'healthy' : 'degraded',
    database: dbConnected ? 'connected' : 'disconnected',
    timestamp: new Date().toISOString()
  });
});

// Catch-all: serve index.html for SPA routing (Express 5 syntax)
app.get('/{*splat}', (req, res) => {
  res.sendFile(path.join(__dirname, '..', 'public', 'index.html'));
});

// Start server
async function start() {
  // Test database connection first
  const dbOk = await testConnection();
  if (!dbOk) {
    console.error('Warning: Database connection failed. API endpoints may not work.');
  }

  app.listen(PORT, () => {
    console.log(`
╔════════════════════════════════════════════════════════╗
║  Shipment Risk Dashboard                               ║
║  Running on http://localhost:${PORT}                      ║
╚════════════════════════════════════════════════════════╝
    `);
  });
}

start();
