import Fastify from 'fastify';
import cors from '@fastify/cors';
import { getFastifyLoggerConfig } from './utils/logger';

// Import routes
{{ROUTE_IMPORTS}}

// Import plugins
import prismaPlugin from './plugins/prisma';

async function start() {
  const fastify = Fastify({
    logger: getFastifyLoggerConfig(),
    requestIdLogLabel: 'reqId',
    genReqId: () => {
      // Generate unique request ID for correlation
      return `req-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    },
  });

  // Log startup
  fastify.log.info({
    node_env: process.env.NODE_ENV || 'development',
    node_version: process.version,
  }, 'Starting DataBridge API server...');

  // Register plugins
  await fastify.register(cors, { 
    origin: process.env.CORS_ORIGIN || '*',
    credentials: true,
  });
  
  await fastify.register(prismaPlugin);

  // Register routes
  {{ROUTE_REGISTRATIONS}}

  // Health check endpoint
  fastify.get('/health', async (request, reply) => {
    const health: any = {
      status: 'ok',
      timestamp: new Date().toISOString(),
      uptime: process.uptime(),
      environment: process.env.NODE_ENV || 'development',
      version: process.env.npm_package_version || '1.0.0',
    };
    
    // Check database connection
    try {
      await (fastify as any).prisma.$queryRaw`SELECT 1`;
      health.database = 'connected';
    } catch (error) {
      health.database = 'disconnected';
      health.status = 'degraded';
    }
    
    return reply.send(health);
  });

  // Metrics endpoint (for monitoring)
  fastify.get('/metrics', async () => {
    return {
      memory: process.memoryUsage(),
      uptime: process.uptime(),
      timestamp: new Date().toISOString(),
    };
  });

  // Graceful shutdown
  const signals = ['SIGTERM', 'SIGINT'];
  for (const signal of signals) {
    process.on(signal, async () => {
      fastify.log.info(`Received ${signal}, starting graceful shutdown...`);
      
      try {
        await fastify.close();
        fastify.log.info('Server closed gracefully');
        process.exit(0);
      } catch (error) {
        fastify.log.error(error, 'Error during shutdown');
        process.exit(1);
      }
    });
  }

  // Start server
  const port = parseInt(process.env.API_PORT || '{{PORT}}', 10);
  const host = process.env.API_HOST || '0.0.0.0';
  
  try {
    await fastify.listen({ port, host });
    
    fastify.log.info({
      port,
      host,
    }, '✅ DataBridge API Server running');
    
    console.log(`\n✅ DataBridge API Server running on http://localhost:${port}\n`);
    console.log('Available routes:');
    console.log('  GET    /health');
    console.log('  GET    /metrics');
    {{ROUTE_LIST}}
    console.log('');
  } catch (error) {
    fastify.log.error(error, 'Failed to start server');
    process.exit(1);
  }
}

start();
