/**
 * ═══════════════════════════════════════════════════════════
 * 🐍 OPHION - Example Node.js Application
 * This app is automatically instrumented by OpenTelemetry
 * No code changes needed - just env vars!
 * ═══════════════════════════════════════════════════════════
 */

const http = require('http');

const PORT = process.env.PORT || 3000;

// Simple HTTP server
const server = http.createServer((req, res) => {
  const { url, method } = req;
  
  console.log(`[${new Date().toISOString()}] ${method} ${url}`);
  
  // Route handling
  if (url === '/health') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ status: 'healthy', service: 'nodejs-example' }));
    return;
  }
  
  if (url === '/') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ 
      message: 'Hello from Node.js!',
      instrumented: true,
      otelEndpoint: process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'not set'
    }));
    return;
  }
  
  if (url === '/api/users') {
    // Simulate some work
    setTimeout(() => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify([
        { id: 1, name: 'Alice' },
        { id: 2, name: 'Bob' },
        { id: 3, name: 'Charlie' }
      ]));
    }, Math.random() * 100);
    return;
  }
  
  if (url === '/api/slow') {
    // Simulate slow operation (good for testing traces)
    setTimeout(() => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ message: 'Slow response', delay: '500ms' }));
    }, 500);
    return;
  }
  
  // 404
  res.writeHead(404, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ error: 'Not Found' }));
});

server.listen(PORT, () => {
  console.log(`🚀 Node.js server running on port ${PORT}`);
  console.log(`📊 OTEL Endpoint: ${process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'not configured'}`);
  console.log(`🏷️  Service Name: ${process.env.OTEL_SERVICE_NAME || 'unknown'}`);
});
