// Google Analytics router — ESM conversion of google-server/routes/analytics.routes.js.
// All routes are read-only — authenticated-only is sufficient; no extra permission.
// google_write is reserved for future write endpoints (per migration 005).

import express from 'express';
import { AnalyticsService } from '../../services/google/analytics.service.js';

export function createGoogleRouter({ redis }) {
  const router = express.Router();
  const service = new AnalyticsService(redis);

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

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

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

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

  return router;
}
