const express = require('express');
const router = express.Router();
const analyticsService = require('../services/analytics.service');

// Basic metrics endpoint
router.get('/metrics', async (req, res) => {
  try {
    const { startDate = '7daysAgo' } = req.query;
    console.log(`Fetching metrics with startDate: ${startDate}`);
    
    const data = await analyticsService.getBasicMetrics(startDate);
    res.json({ success: true, data });
  } catch (error) {
    console.error('Metrics error:', {
      startDate: req.query.startDate,
      error: error.message,
      stack: error.stack
    });
    
    res.status(500).json({
      success: false,
      error: 'Failed to fetch metrics',
      details: error.message
    });
  }
});

// Realtime basic data endpoint
router.get('/realtime/basic', async (req, res) => {
  try {
    console.log('Fetching realtime basic data');
    const data = await analyticsService.getRealTimeBasicData();
    res.json({ success: true, data });
  } catch (error) {
    console.error('Realtime basic error:', {
      error: error.message,
      stack: error.stack
    });
    
    res.status(500).json({
      success: false,
      error: 'Failed to fetch realtime basic data',
      details: error.message
    });
  }
});

// Realtime detailed data endpoint
router.get('/realtime/detailed', async (req, res) => {
  try {
    console.log('Fetching realtime detailed data');
    const data = await analyticsService.getRealTimeDetailedData();
    res.json({ success: true, data });
  } catch (error) {
    console.error('Realtime detailed error:', {
      error: error.message,
      stack: error.stack
    });
    
    res.status(500).json({
      success: false,
      error: 'Failed to fetch realtime detailed data',
      details: error.message
    });
  }
});

// User behavior endpoint
router.get('/user-behavior', async (req, res) => {
  try {
    const { timeRange = '30' } = req.query;
    console.log(`Fetching user behavior with timeRange: ${timeRange}`);
    
    const data = await analyticsService.getUserBehavior(timeRange);
    res.json({ success: true, data });
  } catch (error) {
    console.error('User behavior error:', {
      timeRange: req.query.timeRange,
      error: error.message,
      stack: error.stack
    });
    
    res.status(500).json({
      success: false,
      error: 'Failed to fetch user behavior data',
      details: error.message
    });
  }
});

module.exports = router; 