import { Router } from 'express';
import { authenticate } from '../../middleware/auth.middleware';
import { requireRole } from '../../middleware/rbac.middleware';
import { validate } from '../../middleware/validate';
import { ANALYTICS_ROLES } from '../../utils/roles';
import { analyticsService } from './analytics.service';
import { analyticsQuerySchema, userAnalyticsQuerySchema, userDetailQuerySchema } from './analytics.schemas';

export const analyticsAdminRouter = Router();
analyticsAdminRouter.use(authenticate);
analyticsAdminRouter.use(requireRole(...ANALYTICS_ROLES));

// GET /api/analytics/overview?days=30
analyticsAdminRouter.get(
  '/overview',
  validate(analyticsQuerySchema, 'query'),
  async (req, res, next) => {
    try {
      const days = Number(req.query.days) || 30;
      const overview = await analyticsService.getOverview(days);
      res.json(overview);
    } catch (err) {
      next(err);
    }
  },
);

// GET /api/analytics/geo?days=30
analyticsAdminRouter.get(
  '/geo',
  validate(analyticsQuerySchema, 'query'),
  async (req, res, next) => {
    try {
      const days = Number(req.query.days) || 30;
      const geo = await analyticsService.getGeoAnalytics(days);
      res.json(geo);
    } catch (err) {
      next(err);
    }
  },
);

// GET /api/analytics/content?days=30&module=all
analyticsAdminRouter.get(
  '/content',
  validate(analyticsQuerySchema, 'query'),
  async (req, res, next) => {
    try {
      const days = Number(req.query.days) || 30;
      const module = String(req.query.module || 'all');
      const content = await analyticsService.getContentAnalytics(days, module);
      res.json(content);
    } catch (err) {
      next(err);
    }
  },
);

// GET /api/analytics/users?days=30&page=1&limit=20
analyticsAdminRouter.get(
  '/users',
  validate(userAnalyticsQuerySchema, 'query'),
  async (req, res, next) => {
    try {
      const days = Number(req.query.days) || 30;
      const page = Number(req.query.page) || 1;
      const limit = Number(req.query.limit) || 20;
      const engagement = await analyticsService.getUsersEngagement(days, page, limit);
      res.json(engagement);
    } catch (err) {
      next(err);
    }
  },
);

// GET /api/analytics/users/:userId?days=30
analyticsAdminRouter.get(
  '/users/:userId',
  validate(userDetailQuerySchema, 'query'),
  async (req, res, next) => {
    try {
      const days = Number(req.query.days) || 30;
      const activity = await analyticsService.getUserActivity(String(req.params.userId), days);
      res.json(activity);
    } catch (err) {
      next(err);
    }
  },
);
