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

const registrationService = new GameRegistrationService();

export const gameRegistrationRouter = router({
  /**
   * Register a new game
   */
  registerGame: protectedProcedure
    .input(
      z.object({
        gameId: z.string(),
        gameName: z.string(),
        gameType: z.enum(['slot', 'table', 'card', 'arcade', 'puzzle', 'skill']),
        description: z.string(),
        developer: z.string(),
        metadata: z.object({
          minBet: z.number(),
          maxBet: z.number(),
          rtp: z.number(),
          volatility: z.enum(['low', 'medium', 'high']),
          paylines: z.number().optional(),
          reels: z.number().optional(),
          features: z.array(z.string()),
          theme: z.string(),
          tags: z.array(z.string()),
        }),
        deployment: z.object({
          url: z.string(),
          s3Key: z.string(),
          previewUrl: z.string(),
          testingUrl: z.string(),
        }),
      })
    )
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return registrationService.registerGame(
        input.gameId,
        input.gameName,
        input.gameType,
        input.description,
        input.developer,
        input.metadata,
        input.deployment
      );
    }),

  /**
   * Get registered game
   */
  getRegisteredGame: protectedProcedure
    .input(z.object({ gameId: z.string() }))
    .query(({ input }) => {
      return registrationService.getRegisteredGame(input.gameId);
    }),

  /**
   * Get all registered games
   */
  getAllRegisteredGames: protectedProcedure
    .input(z.object({ status: z.string().optional() }))
    .query(({ input }) => {
      return registrationService.getAllRegisteredGames(input.status);
    }),

  /**
   * Update game status
   */
  updateGameStatus: protectedProcedure
    .input(z.object({ gameId: z.string(), status: z.string() }))
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return registrationService.updateGameStatus(input.gameId, input.status);
    }),

  /**
   * Update game performance
   */
  updateGamePerformance: protectedProcedure
    .input(
      z.object({
        gameId: z.string(),
        metrics: z.object({
          plays: z.number().optional(),
          wagers: z.number().optional(),
          payouts: z.number().optional(),
          sessionLength: z.number().optional(),
          retention: z.number().optional(),
        }),
      })
    )
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return registrationService.updateGamePerformance(input.gameId, input.metrics);
    }),

  /**
   * Create game template
   */
  createGameTemplate: protectedProcedure
    .input(
      z.object({
        templateName: z.string(),
        genre: z.enum(['slot', 'table', 'card', 'arcade', 'puzzle', 'skill']),
        description: z.string(),
        baseGameId: z.string(),
        metadata: z.record(z.any()),
        documentation: z.string(),
      })
    )
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      const baseGame = registrationService.getRegisteredGame(input.baseGameId);
      if (!baseGame) {
        throw new Error('Base game not found');
      }

      return registrationService.createGameTemplate(
        input.templateName,
        input.genre,
        input.description,
        baseGame,
        input.metadata,
        input.documentation
      );
    }),

  /**
   * Get game template
   */
  getGameTemplate: protectedProcedure
    .input(z.object({ templateId: z.string() }))
    .query(({ input }) => {
      return registrationService.getGameTemplate(input.templateId);
    }),

  /**
   * Get templates by genre
   */
  getTemplatesByGenre: protectedProcedure
    .input(z.object({ genre: z.string() }))
    .query(({ input }) => {
      return registrationService.getTemplatesByGenre(input.genre);
    }),

  /**
   * Create deployment workflow
   */
  createDeploymentWorkflow: protectedProcedure
    .input(z.object({ gameId: z.string() }))
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return registrationService.createDeploymentWorkflow(input.gameId);
    }),

  /**
   * Get deployment workflow
   */
  getDeploymentWorkflow: protectedProcedure
    .input(z.object({ workflowId: z.string() }))
    .query(({ input }) => {
      return registrationService.getDeploymentWorkflow(input.workflowId);
    }),

  /**
   * Get game deployment status
   */
  getGameDeploymentStatus: protectedProcedure
    .input(z.object({ gameId: z.string() }))
    .query(({ input }) => {
      return registrationService.getGameDeploymentStatus(input.gameId);
    }),

  /**
   * Update workflow step
   */
  updateWorkflowStep: protectedProcedure
    .input(
      z.object({
        workflowId: z.string(),
        step: z.enum(['validation', 'testing', 'approval', 'deployment']),
        completed: z.boolean(),
        error: z.string().optional(),
      })
    )
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return registrationService.updateWorkflowStep(input.workflowId, input.step, input.completed, input.error);
    }),

  /**
   * Get games by status
   */
  getGamesByStatus: protectedProcedure
    .input(z.object({ status: z.string() }))
    .query(({ input }) => {
      return registrationService.getGamesByStatus(input.status);
    }),

  /**
   * Get top performing games
   */
  getTopPerformingGames: protectedProcedure
    .input(z.object({ limit: z.number().default(10) }))
    .query(({ input }) => {
      return registrationService.getTopPerformingGames(input.limit);
    }),

  /**
   * Get games by type
   */
  getGamesByType: protectedProcedure
    .input(z.object({ gameType: z.string() }))
    .query(({ input }) => {
      return registrationService.getGamesByType(input.gameType);
    }),

  /**
   * Get game statistics
   */
  getGameStatistics: protectedProcedure
    .input(z.object({ gameId: z.string() }))
    .query(({ input }) => {
      return registrationService.getGameStatistics(input.gameId);
    }),

  /**
   * Publish game
   */
  publishGame: protectedProcedure
    .input(z.object({ gameId: z.string() }))
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return registrationService.publishGame(input.gameId);
    }),

  /**
   * Archive game
   */
  archiveGame: protectedProcedure
    .input(z.object({ gameId: z.string() }))
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return registrationService.archiveGame(input.gameId);
    }),

  /**
   * Get all templates
   */
  getAllTemplates: protectedProcedure.query(() => {
    return registrationService.getAllTemplates();
  }),

  /**
   * Get template statistics
   */
  getTemplateStatistics: protectedProcedure
    .input(z.object({ templateId: z.string() }))
    .query(({ input }) => {
      return registrationService.getTemplateStatistics(input.templateId);
    }),
});

export default gameRegistrationRouter;
