const express = require('express');
const http = require('http');
const https = require('https');
const { sslConfig, serverConfig } = require('./config/config');
const corsMiddleware = require('./middleware/cors');

// Import routes
const jerseyRoutes = require('./routes/jersey');
const tshirtRoutes = require('./routes/tshirt');
const merchbayRoutes = require('./routes/merchbay');
const maskRoutes = require('./routes/mask');

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

// Apply CORS middleware globally
app.use(corsMiddleware);

// Health check endpoint
app.get('/health', (req, res) => {
  res.status(200).json({ 
    status: 'healthy',
    service: 'screenshot-service',
    timestamp: new Date().toISOString()
  });
});

// Mount route modules
app.use('/jersey', jerseyRoutes);
app.use('/tshirt', tshirtRoutes);
app.use('/merchbay', merchbayRoutes);
app.use('/mask', maskRoutes);

// Legacy route compatibility (backwards compatibility)
// Map old routes to new structure
app.get('/tb/:designId', (req, res) => {
  console.log('Legacy route /tb/:designId - redirecting to /jersey/:designId');
  req.url = `/jersey/${req.params.designId}`;
  jerseyRoutes(req, res);
});

app.get('/ap/:designId', (req, res) => {
  console.log('Legacy route /ap/:designId - redirecting to /tshirt/allover/:designId');
  req.url = `/tshirt/allover/${req.params.designId}`;
  tshirtRoutes(req, res);
});

// 404 handler for unmatched routes
app.use((req, res) => {
  res.status(404).json({ 
    error: 'Route not found',
    path: req.path,
    method: req.method
  });
});

// Global error handler
app.use((err, req, res, next) => {
  console.error('Unhandled error:', err);
  res.status(500).json({ 
    error: 'Internal server error',
    message: err.message 
  });
});

// Create HTTP or HTTPS server based on configuration
const server = serverConfig.useSSL && sslConfig
  ? https.createServer(sslConfig, app)
  : http.createServer(app);

const protocol = serverConfig.useSSL && sslConfig ? 'https' : 'http';
const sslNote = serverConfig.useSSL && sslConfig ? '(Direct SSL)' : '(SSL via Traefik/Reverse Proxy)';

// Start server
server.listen(serverConfig.port, serverConfig.host, () => {
  console.log('╔════════════════════════════════════════════════════════════╗');
  console.log('║     Screenshot Service - Unified Application Started      ║');
  console.log('╚════════════════════════════════════════════════════════════╝');
  console.log('');
  console.log(`  🚀 Server running on: ${protocol}://${serverConfig.host}:${serverConfig.port}`);
  console.log(`  🔒 SSL Mode: ${sslNote}`);
  console.log('');
  console.log('  📍 Available Routes:');
  console.log('     ├─ /health                      - Health check');
  console.log('     ├─ /jersey/:designId            - Jersey screenshots (4 views)');
  console.log('     ├─ /tshirt/:designId            - T-Shirt screenshots (4 views)');
  console.log('     ├─ /tshirt/allover/:designId    - T-Shirt all-over print (2 views)');
  console.log('     ├─ /merchbay/tshirt/:designId   - Merchbay T-Shirt (4 views)');
  console.log('     ├─ /merchbay/allover/:designId  - Merchbay all-over print (2 views)');
  console.log('     ├─ /merchbay/legacy/:designId   - Merchbay legacy viewer (4 views)');
  console.log('     ├─ /mask/:designId              - All-over print mask');
  console.log('     └─ /mask/classic/:designId      - Classic mask');
  console.log('');
  console.log('  🔄 Legacy Routes (Backwards Compatible):');
  console.log('     ├─ /tb/:designId  → /jersey/:designId');
  console.log('     └─ /ap/:designId  → /tshirt/allover/:designId');
  console.log('');
  console.log('════════════════════════════════════════════════════════════');
});

// Graceful shutdown
process.on('SIGTERM', () => {
  console.log('SIGTERM signal received: closing server');
  server.close(() => {
    console.log('Server closed');
    process.exit(0);
  });
});

process.on('SIGINT', () => {
  console.log('SIGINT signal received: closing server');
  server.close(() => {
    console.log('Server closed');
    process.exit(0);
  });
});
