import express from 'express';
import { QueryProfiler } from '../utils/queryProfiler.js';
import { rawQuery } from '../db.js';
import { pgPool } from '../db.js';

const router = express.Router();

/**
 * GET /api/performance/stats
 * Get aggregated query performance statistics
 */
router.get('/stats', (req, res) => {
  try {
    const { queryName } = req.query;
    const stats = QueryProfiler.getStats(queryName);
    
    res.json({
      success: true,
      stats,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

/**
 * GET /api/performance/slow-queries
 * Get slow queries (default: > 1000ms)
 */
router.get('/slow-queries', (req, res) => {
  try {
    const threshold = parseInt(req.query.threshold || 1000);
    const slowQueries = QueryProfiler.getSlowQueries(threshold);
    
    res.json({
      success: true,
      threshold,
      count: slowQueries.length,
      queries: slowQueries,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

/**
 * POST /api/performance/explain
 * Get EXPLAIN plan for a query
 */
router.post('/explain', async (req, res) => {
  try {
    const { query, params = [] } = req.body;
    
    if (!query) {
      return res.status(400).json({ 
        success: false,
        error: 'Query is required in request body' 
      });
    }
    
    // Get explain plan
    const explainPlan = await QueryProfiler.getExplainPlan(query, params);
    const recommendations = QueryProfiler.analyzeExplainPlan(explainPlan);
    
    res.json({
      success: true,
      explain: explainPlan,
      recommendations,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

/**
 * GET /api/performance/pool-stats
 * Get database connection pool statistics
 */
router.get('/pool-stats', (req, res) => {
  try {
    if (!pgPool) {
      return res.status(503).json({
        success: false,
        error: 'PostgreSQL pool not available'
      });
    }
    
    const stats = {
      totalCount: pgPool.totalCount,
      idleCount: pgPool.idleCount,
      waitingCount: pgPool.waitingCount,
      max: pgPool.options?.max || 'unknown'
    };
    
    res.json({
      success: true,
      pool: stats,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

/**
 * GET /api/performance/metrics
 * Get comprehensive performance metrics
 */
router.get('/metrics', (req, res) => {
  try {
    const poolStats = pgPool ? {
      totalCount: pgPool.totalCount,
      idleCount: pgPool.idleCount,
      waitingCount: pgPool.waitingCount
    } : null;
    
    const queryStats = QueryProfiler.getStats();
    const slowQueries = QueryProfiler.getSlowQueries(1000);
    
    res.json({
      success: true,
      metrics: {
        pool: poolStats,
        queries: queryStats,
        slowQueries: {
          count: slowQueries.length,
          threshold: 1000,
          recent: slowQueries.slice(0, 10) // Last 10 slow queries
        }
      },
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

/**
 * POST /api/performance/clear-metrics
 * Clear all performance metrics
 */
router.post('/clear-metrics', (req, res) => {
  try {
    QueryProfiler.clearMetrics();
    res.json({
      success: true,
      message: 'Metrics cleared',
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

export default router;
