import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import rateLimit from 'express-rate-limit';
import dotenv from 'dotenv';
import { testConnection } from './config/database.js';
import authRoutes from './routes/auth.js';
import processingRoutes from './routes/processing.js';
import paymentRoutes from './routes/payment.js';
import { fileCleanupService } from './services/fileCleanup.js';

dotenv.config();

// Check Sharp availability on startup
const checkSharpInstallation = async () => {
  try {
    const sharp = (await import('sharp')).default;
    console.log('✅ Sharp image processing library loaded successfully');
    return true;
  } catch (error) {
    console.error('❌ Sharp installation issue:', error.message);
    console.log('💡 Try running: npm rebuild sharp --platform=win32 --arch=x64');
    return false;
  }
};

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

// Security middleware
app.use(helmet());
app.use(cors({
  origin: process.env.NODE_ENV === 'production' 
    ? ['https://dev.prasowlabs.in'] 
    : ['http://localhost:3000'],
  credentials: true
}));

// 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);

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

// Static file serving for downloads
app.use('/downloads', express.static('./output'));

// API routes
app.use('/api/auth', authRoutes);
app.use('/api/processing', processingRoutes);
app.use('/api/payment', paymentRoutes);
app.use('/api/payment', paymentRoutes);

// Health check endpoint
app.get('/api/health', async (req, res) => {
  try {
    const dbStatus = await testConnection();
    res.json({
      status: 'healthy',
      timestamp: new Date().toISOString(),
      database: dbStatus ? 'connected' : 'disconnected',
      uptime: process.uptime()
    });
  } catch (error) {
    res.status(500).json({
      status: 'unhealthy',
      error: error.message
    });
  }
});

// Error handling middleware
app.use((error, req, res, next) => {
  console.error('Server error:', error);
  
  if (error.code === 'LIMIT_FILE_SIZE') {
    return res.status(413).json({ 
      error: 'File too large. Maximum file size is 50MB per file.',
      maxSize: '50MB'
    });
  }
  
  if (error.code === 'LIMIT_FILE_COUNT') {
    return res.status(413).json({ 
      error: 'Too many files. Maximum 100 files per batch.',
      maxFiles: 100
    });
  }
  
  if (error.code === 'LIMIT_UNEXPECTED_FILE') {
    return res.status(400).json({ error: 'Unexpected file field. Please use the correct upload field.' });
  }

  if (error.message && error.message.includes('not a supported image format')) {
    return res.status(400).json({ error: error.message });
  }

  res.status(500).json({ 
    error: process.env.NODE_ENV === 'production' 
      ? 'Internal server error' 
      : error.message 
  });
});

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

// Start server
const startServer = async () => {
  try {
    // Test database connection
    const dbConnected = await testConnection();
    if (!dbConnected) {
      console.error('Failed to connect to database. Please check your configuration.');
      process.exit(1);
    }

    // Check Sharp installation
    const sharpAvailable = await checkSharpInstallation();
    if (!sharpAvailable) {
      console.warn('⚠️  Sharp not available - image processing will be limited');
    }

    // Start file cleanup service
    fileCleanupService.startPeriodicCleanup();

    app.listen(PORT, () => {
      console.log(`🚀 Server running on port ${PORT}`);
      console.log(`📊 Environment: ${process.env.NODE_ENV || 'development'}`);
      console.log(`🔗 API Base URL: http://localhost:${PORT}/api`);
      if (!sharpAvailable) {
        console.log('⚠️  Image processing disabled - fix Sharp installation');
      }
    });
  } catch (error) {
    console.error('Failed to start server:', error);
    process.exit(1);
  }
};

startServer();

export default app;