import express from 'express';
import { AircallService } from '../services/aircall/AircallService.js';

export const createAircallRoutes = (config, logger) => {
  const router = express.Router();
  const aircallService = new AircallService(config);

  router.get('/metrics/:timeRange?', async (req, res) => {
    try {
      const { timeRange = 'today' } = req.params;
      const allowedRanges = ['today', 'yesterday', 'last7days', 'last30days', 'last90days'];
      
      if (!allowedRanges.includes(timeRange)) {
        return res.status(400).json({ 
          error: 'Invalid time range',
          allowedRanges 
        });
      }

      const metrics = await aircallService.getMetrics(timeRange);
      
      res.json({
        ...metrics,
        _meta: {
          timeRange,
          generatedAt: new Date().toISOString(),
          dataPoints: metrics.daily_data?.length || 0
        }
      });
    } catch (error) {
      logger.error('Error fetching Aircall metrics:', error);
      res.status(500).json({ 
        error: 'Failed to fetch Aircall metrics',
        message: error.message 
      });
    }
  });

  // Health check endpoint
  router.get('/health', (req, res) => {
    const mongoConnected = !!aircallService.mongodb?.db;
    const redisConnected = !!aircallService.redis?.isOpen;
    
    const health = {
      status: mongoConnected && redisConnected ? 'ok' : 'degraded',
      service: 'aircall',
      timestamp: new Date().toISOString(),
      connections: {
        mongodb: mongoConnected,
        redis: redisConnected
      }
    };
    res.json(health);
  });

  return router;
}; 