require('dotenv').config();

const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const session = require('express-session');
const morgan = require('morgan');

// Import database (uses environment variables from docker-compose.yml)
const database = require('./config/database');

// Import services
const DiffProcessingService = require('./services/diff-processing.service');

// Import routes
const githubRoutes = require('./routes/github-integration.routes');
const githubOAuthRoutes = require('./routes/github-oauth');
const webhookRoutes = require('./routes/webhook.routes');
const vcsRoutes = require('./routes/vcs.routes');
const aiStreamingRoutes = require('./routes/ai-streaming.routes');
const diffViewerRoutes = require('./routes/diff-viewer.routes');

// Enhanced routes removed as requested

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

// Middleware
app.use(helmet());
app.use(cors({
  origin: function (origin, callback) {
    // Allow all origins in development
    callback(null, true);
  },
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
  credentials: true,
  allowedHeaders: [
    'Content-Type', 
    'Authorization', 
    'X-Requested-With',
    'Origin',
    'Accept',
    'Cache-Control',
    'Pragma'
  ],
  exposedHeaders: [
    'Content-Length', 
    'X-Total-Count'
  ]
}));

// Handle preflight OPTIONS requests
app.options('*', (req, res) => {
  res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, PATCH');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With, Origin, Accept, Cache-Control, Pragma');
  res.header('Access-Control-Allow-Credentials', 'true');
  res.sendStatus(200);
});

app.use(morgan('combined'));
// Preserve raw body for webhook signature verification

app.use(express.json({
  limit: '10mb',
  verify: (req, res, buf) => {
    req.rawBody = buf;
  }
}));

app.use(express.urlencoded({
  extended: true,
  verify: (req, res, buf) => {
    req.rawBody = buf;
  }
}));

// Session middleware
app.use(session({
  secret: process.env.SESSION_SECRET || 'git-integration-secret-key-2024',
  resave: false,
  saveUninitialized: false,
  cookie: {
    secure: false, // Set to true if using HTTPS
    httpOnly: true,
    maxAge: 24 * 60 * 60 * 1000 // 24 hours
  }
}));

// Routes
app.use('/api/github', githubRoutes);
app.use('/api/github', githubOAuthRoutes);
app.use('/api/github', webhookRoutes);
app.use('/api/vcs', vcsRoutes);
app.use('/api/ai', aiStreamingRoutes);
app.use('/api/diffs', diffViewerRoutes);

// Enhanced routes removed as requested

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

// API health check endpoint for gateway compatibility
app.get('/api/github/health', (req, res) => {
  res.status(200).json({
    status: 'healthy',
    service: 'git-integration',
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    version: '1.0.0'
  });
});

// Root endpoint
app.get('/', (req, res) => {
  res.json({
    message: 'Git Integration Service',
    version: '1.0.0',
    endpoints: {
      health: '/health',
      github: '/api/github',
      oauth: '/api/github/auth',
      webhook: '/api/github/webhook',
      vcs: '/api/vcs/:provider',
      // Enhanced routes removed as requested
    }
  });
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error('Error:', err);
  res.status(500).json({
    success: false,
    message: 'Internal server error',
    error: process.env.NODE_ENV === 'development' ? err.message : 'Something went wrong'
  });
});

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

// Graceful shutdown
process.on('SIGTERM', async () => {
  console.log('SIGTERM received, shutting down gracefully');
  await database.close();
  process.exit(0);
});

process.on('SIGINT', async () => {
  console.log('SIGINT received, shutting down gracefully');
  await database.close();
  process.exit(0);
});

// Initialize services
async function initializeServices() {
  try {
    // Initialize diff processing service
    const diffProcessingService = new DiffProcessingService();
    
    console.log('✅ All services initialized successfully');
  } catch (error) {
    console.error('❌ Error initializing services:', error);
  }
}

// Start server
app.listen(PORT, '0.0.0.0', async () => {
  console.log(`🚀 Git Integration Service running on port ${PORT}`);
  console.log(`📊 Health check: http://localhost:8000/health`);
  console.log(`🔗 GitHub API: http://localhost:8000/api/github`);
  // Enhanced routes removed as requested
  
  // Initialize services after server starts
  await initializeServices();
});


// WebSocket service initialization removed - not needed for basic functionality



module.exports = app;
