import express from 'express';
import path from 'path';
import { createServer as createViteServer } from 'vite';
import apiApp, { initDb } from './server/api-mongodb.js';

async function startServer() {
  // Initialize MongoDB
  try {
    await initDb();
  } catch (err) {
    console.error('Failed to initialize MongoDB:', err);
    if (process.env.NODE_ENV === 'production') {
      process.exit(1);
    } else {
      console.warn('Continuing in development mode without database connection.');
    }
  }

  const app = express();
  const PORT = 3000;
  const HOST = '0.0.0.0';

  // Mount API routes
  app.use(apiApp);

  // Vite middleware for development or static serving for production
  if (process.env.NODE_ENV !== 'production') {
    const vite = await createViteServer({
      server: { 
        middlewareMode: true,
        hmr: false,
      },
      appType: 'spa',
    });
    app.use(vite.middlewares);
  } else {
    const distPath = path.join(process.cwd(), 'dist');
    app.use(express.static(distPath));
    app.get('*', (_req, res) => {
      res.sendFile(path.join(distPath, 'index.html'));
    });
  }

  app.listen(PORT, HOST, () => {
    console.log(`Hospital Server running on http://${HOST}:${PORT}`);
  });
}

startServer();
