import { router, protectedProcedure } from "../_core/trpc.ts";
import { z } from "zod";
import { TRPCError } from "@trpc/server";

export const adminCasinoRouter = router({
  // Get casino configuration
  getCasinoConfig: protectedProcedure.query(async ({ ctx }) => {
    if (ctx.user.role !== "admin") {
      throw new TRPCError({ code: "FORBIDDEN" });
    }

    // In production, query database
    return {
      maxWinPerSpin: 10000,
      maxWinPerSession: 50000,
      minBetAmount: 0.1,
      maxBetAmount: 100,
      defaultRTP: 96.5,
      maintenanceMode: false,
      maintenanceMessage: "",
      autoSpinLimit: 100,
      sessionTimeoutMinutes: 60,
      dailyLossLimit: false,
      dailyLossLimitAmount: 500,
    };
  }),

  // Update casino configuration
  updateCasinoConfig: protectedProcedure
    .input(
      z.object({
        maxWinPerSpin: z.number().positive().optional(),
        maxWinPerSession: z.number().positive().optional(),
        minBetAmount: z.number().positive().optional(),
        maxBetAmount: z.number().positive().optional(),
        defaultRTP: z.number().min(1).max(100).optional(),
        autoSpinLimit: z.number().positive().optional(),
        sessionTimeoutMinutes: z.number().positive().optional(),
        dailyLossLimitAmount: z.number().positive().optional(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      if (ctx.user.role !== "admin") {
        throw new TRPCError({ code: "FORBIDDEN" });
      }

      // In production, update database
      return {
        success: true,
        message: "Casino configuration updated",
      };
    }),

  // Toggle maintenance mode
  toggleMaintenanceMode: protectedProcedure
    .input(
      z.object({
        enabled: z.boolean(),
        message: z.string().optional(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      if (ctx.user.role !== "admin") {
        throw new TRPCError({ code: "FORBIDDEN" });
      }

      // In production, update database
      return {
        success: true,
        message: input.enabled ? "Maintenance mode enabled" : "Maintenance mode disabled",
      };
    }),

  // Toggle daily loss limit
  toggleDailyLossLimit: protectedProcedure
    .input(
      z.object({
        enabled: z.boolean(),
        amount: z.number().positive().optional(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      if (ctx.user.role !== "admin") {
        throw new TRPCError({ code: "FORBIDDEN" });
      }

      // In production, update database
      return {
        success: true,
        message: input.enabled ? "Daily loss limit enabled" : "Daily loss limit disabled",
      };
    }),

  // Get casino statistics
  getCasinoStats: protectedProcedure.query(async ({ ctx }) => {
    if (ctx.user.role !== "admin") {
      throw new TRPCError({ code: "FORBIDDEN" });
    }

    // In production, query database
    return {
      totalRevenue: 0,
      totalPlayers: 0,
      activeGames: 0,
      totalSpins: 0,
      averageRTP: 96.5,
      systemHealth: 99.8,
      lastBackup: new Date(),
    };
  }),

  // Get game categories
  getGameCategories: protectedProcedure.query(async ({ ctx }) => {
    if (ctx.user.role !== "admin") {
      throw new TRPCError({ code: "FORBIDDEN" });
    }

    // In production, query database
    return [
      { name: "Slots", count: 200 },
      { name: "Table Games", count: 50 },
      { name: "Arcade", count: 30 },
      { name: "Jackpots", count: 40 },
      { name: "Live Dealers", count: 20 },
    ];
  }),

  // Update game category
  updateGameCategory: protectedProcedure
    .input(
      z.object({
        categoryId: z.string(),
        name: z.string(),
        description: z.string().optional(),
        isActive: z.boolean().optional(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      if (ctx.user.role !== "admin") {
        throw new TRPCError({ code: "FORBIDDEN" });
      }

      // In production, update database
      return {
        success: true,
        message: "Category updated",
      };
    }),

  // Get providers
  getProviders: protectedProcedure.query(async ({ ctx }) => {
    if (ctx.user.role !== "admin") {
      throw new TRPCError({ code: "FORBIDDEN" });
    }

    // In production, query database
    return [
      { name: "PG Soft", gameCount: 45, revenue: 12500 },
      { name: "Yggdrasil", gameCount: 18, revenue: 8900 },
      { name: "NextGen", gameCount: 13, revenue: 6200 },
      { name: "EGT", gameCount: 52, revenue: 9800 },
      { name: "Playtech", gameCount: 38, revenue: 11200 },
    ];
  }),

  // Update provider settings
  updateProviderSettings: protectedProcedure
    .input(
      z.object({
        providerId: z.string(),
        isActive: z.boolean().optional(),
        commissionRate: z.number().optional(),
        maxGamesPerDay: z.number().optional(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      if (ctx.user.role !== "admin") {
        throw new TRPCError({ code: "FORBIDDEN" });
      }

      // In production, update database
      return {
        success: true,
        message: "Provider settings updated",
      };
    }),

  // Get RTP overrides
  getRTPOverrides: protectedProcedure.query(async ({ ctx }) => {
    if (ctx.user.role !== "admin") {
      throw new TRPCError({ code: "FORBIDDEN" });
    }

    // In production, query database
    return {
      overrides: [],
      total: 0,
    };
  }),

  // Set RTP override for game
  setRTPOverride: protectedProcedure
    .input(
      z.object({
        gameId: z.string(),
        rtp: z.number().min(1).max(100),
        reason: z.string().optional(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      if (ctx.user.role !== "admin") {
        throw new TRPCError({ code: "FORBIDDEN" });
      }

      // In production, update database
      return {
        success: true,
        message: `RTP override set for game ${input.gameId}`,
      };
    }),

  // Get system health
  getSystemHealth: protectedProcedure.query(async ({ ctx }) => {
    if (ctx.user.role !== "admin") {
      throw new TRPCError({ code: "FORBIDDEN" });
    }

    // In production, check actual system status
    return {
      databaseStatus: "healthy" as const,
      apiStatus: "healthy" as const,
      cacheStatus: "healthy" as const,
      storageStatus: "healthy" as const,
      overallHealth: 99.8,
      lastCheck: new Date(),
    };
  }),
});
