import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import { v4 as uuidv4 } from 'uuid';
import logger from './utils/logger.js';
import { pool } from './db/connection.js';
import { errorHandler } from './middleware/errorHandler.js';
import projectRoutes from './routes/projects.js';
import taskRoutes from './routes/tasks.js';

dotenv.config();

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

// ============================================================================
// MIDDLEWARE
// ============================================================================

// CORS
app.use(cors({
  origin: process.env.CORS_ORIGIN || '*',
  credentials: true
}));

// Request ID middleware
app.use((req, res, next) => {
  req.id = req.get('X-Request-ID') || uuidv4();
  res.set('X-Request-ID', req.id);
  next();
});

// Request logging middleware
app.use((req, res, next) => {
  const startTime = Date.now();
  
  res.on('finish', () => {
    const duration = Date.now() - startTime;
    logger.info({
      message: 'HTTP Request',
      request_id: req.id,
      method: req.method,
      path: req.path,
      status: res.statusCode,
      duration_ms: duration,
      user_id: req.user?.id || null
    });
  });
  
  next();
});

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

// ============================================================================
// HEALTH CHECK
// ============================================================================

app.get('/health', async (req, res) => {
  try {
    const startTime = Date.now();
    const result = await pool.query('SELECT NOW()');
    const duration = Date.now() - startTime;
    
    res.json({
      status: 'ok',
      db: 'connected',
      uptime_ms: process.uptime() * 1000,
      db_query_time_ms: duration,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    logger.error({
      message: 'Health check failed',
      request_id: req.id,
      error: error.message
    });
    
    res.status(503).json({
      status: 'error',
      error: {
        code: 'SERVICE_UNAVAILABLE',
        message: 'Database connection failed'
      }
    });
  }
});

// ============================================================================
// ROUTES
// ============================================================================

app.use('/api/v1', projectRoutes);
app.use('/api/v1', taskRoutes);

// ============================================================================
// 404 Handler
// ============================================================================

app.use((req, res) => {
  res.status(404).json({
    status: 'error',
    error: {
      code: 'NOT_FOUND',
      message: `Route ${req.method} ${req.path} not found`
    },
    meta: {
      timestamp: new Date().toISOString(),
      request_id: req.id
    }
  });
});

// ============================================================================
// ERROR HANDLER (Must be last)
// ============================================================================

app.use(errorHandler);

// ============================================================================
// SERVER START
// ============================================================================

const server = app.listen(PORT, () => {
  logger.info({
    message: 'TekDek Command Center API started',
    port: PORT,
    environment: process.env.NODE_ENV || 'development',
    timestamp: new Date().toISOString()
  });
});

// Graceful shutdown
process.on('SIGTERM', () => {
  logger.info({ message: 'SIGTERM received, shutting down gracefully' });
  
  server.close(async () => {
    await pool.end();
    logger.info({ message: 'Server and database connection closed' });
    process.exit(0);
  });
});

process.on('SIGINT', () => {
  logger.info({ message: 'SIGINT received, shutting down gracefully' });
  
  server.close(async () => {
    await pool.end();
    logger.info({ message: 'Server and database connection closed' });
    process.exit(0);
  });
});

export default app;
