/**
 * Backend Entry Point
 * 
 * Purpose: Initialize Express app, apply middleware, mount routes, start server
 * This is where the entire backend application comes together
 */

import express, { Application } from 'express';
import cors from 'cors';
import helmet from 'helmet';
import compression from 'compression';
import { appConfig } from './config/app';
import { requestLogger } from './middlewares/requestLogger';
import { errorHandler } from './middlewares/errorHandler';

// Initialize Express app
const app: Application = express();

// Security middleware
app.use(helmet());
app.use(cors({ origin: appConfig.corsOrigin }));

// Body parsing
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// Compression
app.use(compression());

// Request logging
app.use(requestLogger);

// Health check endpoint
app.get('/health', (req, res) => {
  res.json({ 
    success: true, 
    message: 'Server is running',
    environment: appConfig.env,
    timestamp: new Date().toISOString(),
  });
});

// API Routes
// TODO: Import and mount your route files here
// Example:
// import authRoutes from './routes/auth';
// import productRoutes from './routes/products';
// app.use('/api/auth', authRoutes);
// app.use('/api/products', productRoutes);

// Error handling (must be last)
app.use(errorHandler);

// Start server
const PORT = appConfig.port;
app.listen(PORT, () => {
  console.log(`🚀 Backend server running on http://localhost:${PORT}`);
  console.log(`📝 Environment: ${appConfig.env}`);
  console.log(`🔗 CORS enabled for: ${appConfig.corsOrigin}`);
});

export default app;
