import { router, protectedProcedure } from '../_core/trpc.js.ts';
import { z } from 'zod';
import GamePerformanceMonitoringService from '../gamePerformanceMonitoringService.js';

const monitoringService = new GamePerformanceMonitoringService();

export const gamePerformanceMonitoringRouter = router({
  /**
   * Record game metrics
   */
  recordGameMetrics: protectedProcedure
    .input(
      z.object({
        gameId: z.string(),
        metrics: z.object({
          activePlayers: z.number(),
          totalPlays: z.number(),
          totalWagers: z.number(),
          totalPayouts: z.number(),
          sessionCount: z.number(),
          averageSessionDuration: z.number(),
        }),
      })
    )
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return monitoringService.recordGameMetrics(input.gameId, input.metrics);
    }),

  /**
   * Update game health status
   */
  updateGameHealthStatus: protectedProcedure
    .input(
      z.object({
        gameId: z.string(),
        status: z.enum(['healthy', 'warning', 'critical', 'offline']),
        errorRate: z.number(),
        avgResponseTime: z.number(),
        issues: z.array(z.string()).optional(),
      })
    )
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return monitoringService.updateGameHealthStatus(
        input.gameId,
        input.status,
        input.errorRate,
        input.avgResponseTime,
        input.issues
      );
    }),

  /**
   * Get game health status
   */
  getGameHealthStatus: protectedProcedure
    .input(z.object({ gameId: z.string() }))
    .query(({ input }) => {
      return monitoringService.getGameHealthStatus(input.gameId);
    }),

  /**
   * Create performance alert
   */
  createAlert: protectedProcedure
    .input(
      z.object({
        gameId: z.string(),
        alertType: z.enum(['low_engagement', 'high_error_rate', 'revenue_drop', 'player_drop', 'performance_issue']),
        severity: z.enum(['info', 'warning', 'critical']),
        message: z.string(),
        threshold: z.number(),
        currentValue: z.number(),
      })
    )
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return monitoringService.createAlert(
        input.gameId,
        input.alertType,
        input.severity,
        input.message,
        input.threshold,
        input.currentValue
      );
    }),

  /**
   * Get game alerts
   */
  getGameAlerts: protectedProcedure
    .input(z.object({ gameId: z.string() }))
    .query(({ input }) => {
      return monitoringService.getGameAlerts(input.gameId);
    }),

  /**
   * Resolve alert
   */
  resolveAlert: protectedProcedure
    .input(z.object({ alertId: z.string() }))
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return monitoringService.resolveAlert(input.alertId);
    }),

  /**
   * Get latest metrics
   */
  getLatestMetrics: protectedProcedure
    .input(z.object({ gameId: z.string() }))
    .query(({ input }) => {
      return monitoringService.getLatestMetrics(input.gameId);
    }),

  /**
   * Get metrics history
   */
  getMetricsHistory: protectedProcedure
    .input(z.object({ gameId: z.string(), limit: z.number().default(50) }))
    .query(({ input }) => {
      return monitoringService.getMetricsHistory(input.gameId, input.limit);
    }),

  /**
   * Track player engagement
   */
  trackPlayerEngagement: protectedProcedure
    .input(
      z.object({
        gameId: z.string(),
        playerId: z.string(),
        engagementType: z.enum(['play', 'win', 'share', 'return']),
      })
    )
    .mutation(({ input }) => {
      monitoringService.trackPlayerEngagement(input.gameId, input.playerId, input.engagementType);
      return { success: true };
    }),

  /**
   * Get engagement metrics
   */
  getEngagementMetrics: protectedProcedure
    .input(z.object({ gameId: z.string() }))
    .query(({ input }) => {
      return monitoringService.getEngagementMetrics(input.gameId);
    }),

  /**
   * Get performance comparison
   */
  getPerformanceComparison: protectedProcedure
    .input(z.object({ gameIds: z.array(z.string()) }))
    .query(({ input }) => {
      return monitoringService.getPerformanceComparison(input.gameIds);
    }),

  /**
   * Get performance trends
   */
  getPerformanceTrends: protectedProcedure
    .input(z.object({ gameId: z.string(), timeWindow: z.number().default(24) }))
    .query(({ input }) => {
      return monitoringService.getPerformanceTrends(input.gameId, input.timeWindow);
    }),

  /**
   * Get all health statuses
   */
  getAllHealthStatuses: protectedProcedure.query(() => {
    return monitoringService.getAllHealthStatuses();
  }),

  /**
   * Get critical games
   */
  getCriticalGames: protectedProcedure.query(() => {
    return monitoringService.getCriticalGames();
  }),

  /**
   * Get performance summary
   */
  getPerformanceSummary: protectedProcedure.query(() => {
    return monitoringService.getPerformanceSummary();
  }),

  /**
   * Get active connections count
   */
  getActiveConnectionsCount: protectedProcedure
    .input(z.object({ gameId: z.string() }))
    .query(({ input }) => {
      return monitoringService.getActiveConnectionsCount(input.gameId);
    }),

  /**
   * Get all active games
   */
  getAllActiveGames: protectedProcedure.query(() => {
    return monitoringService.getAllActiveGames();
  }),
});

export default gamePerformanceMonitoringRouter;
