import express from 'express';
import { getDbConnection, getCachedQuery } from '../db/connection.js';

const router = express.Router();

// Test endpoint to count orders
router.get('/order-count', async (req, res) => {
  try {
    const { connection } = await getDbConnection();
    
    // Simple query to count orders from _order table
    const queryFn = async () => {
      const [rows] = await connection.execute('SELECT COUNT(*) as count FROM _order');
      return rows[0].count;
    };
    
    const cacheKey = 'order-count';
    const count = await getCachedQuery(cacheKey, 'default', queryFn);
    
    res.json({
      success: true,
      data: {
        orderCount: count,
        timestamp: new Date().toISOString()
      }
    });
  } catch (error) {
    console.error('Error fetching order count:', error);
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// Test connection endpoint
router.get('/test-connection', async (req, res) => {
  try {
    const { connection } = await getDbConnection();
    
    // Test the connection with a simple query
    const [rows] = await connection.execute('SELECT 1 as test');
    
    res.json({
      success: true,
      message: 'Database connection successful',
      data: rows[0]
    });
  } catch (error) {
    console.error('Error testing connection:', error);
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

export default router; 