import { router, adminProcedure } from "../_core/trpc.ts";
import { z } from "zod";
import {
  generateRtpRecommendations,
  getGameMetrics,
  applyRtpAdjustment,
  getGamesNeedingAdjustment,
  batchApplyRtpAdjustments,
} from "../services/rtpAdjustmentEngine.ts";

export const rtpAdjustmentAdminRouter = router({
  // Get RTP adjustment recommendations for a specific game
  getRecommendation: adminProcedure
    .input(z.object({ gameId: z.number() }))
    .query(async ({ input }) => {
      const recommendation = await generateRtpRecommendations(input.gameId);
      return recommendation;
    }),

  // Get detailed metrics for a game
  getGameMetrics: adminProcedure
    .input(
      z.object({
        gameId: z.number(),
        days: z.number().min(1).max(90).default(7),
      })
    )
    .query(async ({ input }) => {
      const metrics = await getGameMetrics(input.gameId, input.days);
      return metrics;
    }),

  // Get all games needing RTP adjustment
  getGamesNeedingAdjustment: adminProcedure
    .input(z.object({ limit: z.number().min(1).max(50).default(10) }))
    .query(async ({ input }) => {
      const recommendations = await getGamesNeedingAdjustment(input.limit);
      return recommendations;
    }),

  // Apply RTP adjustment to a game
  applyAdjustment: adminProcedure
    .input(
      z.object({
        gameId: z.number(),
        newRtp: z.number().min(70).max(99),
        reason: z.string(),
      })
    )
    .mutation(async ({ input, ctx }) => {
      try {
        await applyRtpAdjustment(input.gameId, input.newRtp, input.reason, ctx.user.id);

        return {
          success: true,
          message: `RTP adjusted to ${input.newRtp}%`,
          gameId: input.gameId,
        };
      } catch (error) {
        throw new Error(`Failed to apply RTP adjustment: ${error}`);
      }
    }),

  // Batch apply RTP adjustments (dry run first)
  batchApplyAdjustments: adminProcedure
    .input(z.object({ dryRun: z.boolean().default(true) }))
    .mutation(async ({ input, ctx }) => {
      const result = await batchApplyRtpAdjustments(ctx.user.id, input.dryRun);

      return {
        success: true,
        dryRun: input.dryRun,
        applied: result.applied,
        skipped: result.skipped,
        adjustments: result.adjustments,
        message: input.dryRun
          ? `Dry run: ${result.adjustments.length} adjustments ready to apply`
          : `Applied ${result.applied} adjustments, skipped ${result.skipped}`,
      };
    }),
});
