import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import compression from 'compression';
import rateLimit from 'express-rate-limit';
import path from 'path';
import { config } from './config/config';
import { errorHandler } from './middleware/errorHandler';
import { requestLogger } from './middleware/requestLogger';

// Route imports
import recipeRoutes from './routes/recipes';
import ingredientRoutes from './routes/ingredients';
import imageRoutes from './routes/images';
import healthRoutes from './routes/health';

const app = express();

// Security middleware
app.use(helmet({
  crossOriginResourcePolicy: { policy: "cross-origin" },
}));
app.use(compression());

// Rate limiting
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // limit each IP to 100 requests per windowMs
  message: 'Too many requests from this IP, please try again later.',
});
app.use(limiter);

// CORS configuration - Allow both development and production origins
const allowedOrigins = [
  'http://localhost:5173', // Vite dev server
  'http://localhost:3000', // Docker frontend
  config.cors.origin       // Environment configured origin
].filter(Boolean);

// Add local network origins if CORS_ORIGIN is "*" (for local network access)
const corsConfig = config.cors.origin === '*' 
  ? {
      origin: true, // Allow all origins for local network
      credentials: true,
    }
  : {
      origin: allowedOrigins,
      credentials: true,
    };

app.use(cors(corsConfig));

// Additional CORS headers for all requests
app.use((req, res, next) => {
  const origin = req.headers.origin;
  
  if (config.cors.origin === '*') {
    // Allow all origins for local network access
    res.header('Access-Control-Allow-Origin', origin || '*');
  } else if (origin && allowedOrigins.includes(origin)) {
    res.header('Access-Control-Allow-Origin', origin);
  }
  res.header('Access-Control-Allow-Credentials', 'true');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  
  if (req.method === 'OPTIONS') {
    return res.sendStatus(200);
  }
  next();
});

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

// Request logging
app.use(requestLogger);

// Static file serving for uploads
app.use('/uploads', express.static(path.join(process.cwd(), 'uploads')));

// API routes
app.use('/api/health', healthRoutes);
app.use('/api/recipes', recipeRoutes);
app.use('/api/ingredients', ingredientRoutes);
app.use('/api/images', imageRoutes);

// Direct image serving (for convenience)
app.get('/serve/*', (req, res, next) => {
  const imagePath = (req.params as any)[0]; // Get everything after /serve/
  // Remove leading 'uploads/' if present to avoid duplication
  const cleanPath = imagePath.replace(/^uploads\//, '');
  const fullPath = path.join(process.cwd(), '../../uploads', cleanPath);
  
  console.log(`Direct serve request: ${req.originalUrl} -> ${fullPath}`);
  
  // Check if file exists
  const fs = require('fs');
  if (!fs.existsSync(fullPath)) {
    return res.status(404).json({
      success: false,
      message: 'Image not found',
      requestedPath: req.originalUrl,
      resolvedPath: fullPath
    });
  }
  
  // Set headers for images
  res.set({
    'Access-Control-Allow-Origin': 'http://localhost:5173',
    'Access-Control-Allow-Credentials': 'true',
    'Cache-Control': 'public, max-age=31536000',
  });
  
  res.sendFile(path.resolve(fullPath));
});

// 404 handler
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    message: `Route ${req.originalUrl} not found`,
  });
});

// Global error handler
app.use(errorHandler);

// Start server
const PORT = config.port;

app.listen(PORT, () => {
  console.log(`🚀 Server running on port ${PORT}`);
  console.log(`📱 Health check: http://localhost:${PORT}/api/health`);
  console.log(`🎯 API Documentation: http://localhost:${PORT}/api`);
});

export default app;