/**
 * tRPC Routers for Advanced Admin Features
 * Handles retention campaigns, activity feed, and revenue forecasting
 */

import { router, publicProcedure, protectedProcedure } from '../_core/trpc.ts';
import { z } from 'zod';
import * as retentionService from '../services/retentionCampaignService.ts';
import * as forecastingService from '../services/revenueForecastingService.ts';

/**
 * Retention Campaign Router
 */
export const retentionCampaignRouter = router({
  // Create a new retention campaign
  createCampaign: protectedProcedure
    .input(
      z.object({
        name: z.string().min(1),
        targetSegment: z.enum(['dormant', 'casual', 'vip', 'new', 'atrisk']),
        offers: z.array(z.string()),
        channels: z.array(z.enum(['email', 'sms', 'push', 'ingame', 'social'])),
        startDate: z.date(),
        endDate: z.date(),
        message: z.string().optional(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      // Verify user is admin
      if (ctx.user?.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      // In production, save to database
      return {
        id: Math.floor(Math.random() * 10000),
        ...input,
        status: 'draft',
        targetAudience: 0,
        reachedAudience: 0,
        conversionRate: 0,
        revenue: 0,
        createdAt: new Date(),
      };
    }),

  // Get all campaigns
  getCampaigns: protectedProcedure
    .input(
      z.object({
        status: z.enum(['draft', 'scheduled', 'active', 'completed', 'paused']).optional(),
        limit: z.number().default(50),
      })
    )
    .query(async ({ ctx, input }) => {
      if (ctx.user?.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      // Mock data - would query database in production
      return [
        {
          id: 1,
          name: 'Dormant Player Reactivation',
          targetSegment: 'dormant',
          status: 'active',
          startDate: new Date('2026-04-10'),
          endDate: new Date('2026-05-10'),
          targetAudience: 3200,
          reachedAudience: 2850,
          conversionRate: 12.5,
          revenue: 45600,
          offers: ['20% Bonus', 'Free Spins', 'Cashback'],
          channels: ['email', 'sms', 'push'],
          createdAt: new Date('2026-04-01'),
        },
      ];
    }),

  // Send campaign
  sendCampaign: protectedProcedure
    .input(z.object({ campaignId: z.number() }))
    .mutation(async ({ ctx, input }) => {
      if (ctx.user?.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      // Get campaign details and send via all channels
      const players = await retentionService.getSegmentPlayers('dormant', 1000);
      
      const results = {
        email: await retentionService.sendCampaignViaEmail(players, 'Campaign', 'Message', []),
        sms: await retentionService.sendCampaignViaSMS(players, 'Campaign', []),
        push: await retentionService.sendCampaignViaPush(players, 'Campaign', 'Message', []),
      };

      return {
        success: true,
        totalSent: results.email.sent + results.sms.sent + results.push.sent,
        totalFailed: results.email.failed + results.sms.failed + results.push.failed,
        results,
      };
    }),

  // Get campaign performance
  getCampaignPerformance: protectedProcedure
    .input(z.object({ campaignId: z.number() }))
    .query(async ({ ctx, input }) => {
      if (ctx.user?.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return await retentionService.getCampaignPerformanceByChannel(input.campaignId);
    }),

  // Pause campaign
  pauseCampaign: protectedProcedure
    .input(z.object({ campaignId: z.number() }))
    .mutation(async ({ ctx, input }) => {
      if (ctx.user?.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      await retentionService.pauseCampaign(input.campaignId);
      return { success: true };
    }),

  // Resume campaign
  resumeCampaign: protectedProcedure
    .input(z.object({ campaignId: z.number() }))
    .mutation(async ({ ctx, input }) => {
      if (ctx.user?.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      await retentionService.resumeCampaign(input.campaignId);
      return { success: true };
    }),

  // Delete campaign
  deleteCampaign: protectedProcedure
    .input(z.object({ campaignId: z.number() }))
    .mutation(async ({ ctx, input }) => {
      if (ctx.user?.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      await retentionService.cancelCampaign(input.campaignId);
      return { success: true };
    }),
});

/**
 * Activity Feed Router
 */
export const activityFeedRouter = router({
  // Get recent activities
  getActivities: protectedProcedure
    .input(
      z.object({
        limit: z.number().default(100),
        eventType: z.enum(['login', 'logout', 'deposit', 'withdrawal', 'win', 'game_play']).optional(),
        userId: z.number().optional(),
      })
    )
    .query(async ({ ctx, input }) => {
      if (ctx.user?.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      // Mock data - would query database in production
      return [
        {
          id: '1',
          userId: 1001,
          username: 'Player_Alpha',
          eventType: 'login',
          timestamp: new Date(),
          ipAddress: '192.168.1.100',
          deviceType: 'Desktop',
        },
      ];
    }),

  // Search activities
  searchActivities: protectedProcedure
    .input(z.object({ query: z.string(), limit: z.number().default(100) }))
    .query(async ({ ctx, input }) => {
      if (ctx.user?.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      // Mock search results
      return [];
    }),

  // Get activity metrics
  getActivityMetrics: protectedProcedure
    .input(
      z.object({
        startDate: z.date(),
        endDate: z.date(),
      })
    )
    .query(async ({ ctx, input }) => {
      if (ctx.user?.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      // Mock metrics
      return [
        {
          timestamp: new Date(),
          logins: 45,
          deposits: 12,
          withdrawals: 5,
          wins: 28,
          gamePlays: 156,
        },
      ];
    }),

  // Get activity summary
  getActivitySummary: protectedProcedure.query(async ({ ctx }) => {
    if (ctx.user?.role !== 'admin') {
      throw new Error('Unauthorized');
    }

    return {
      totalActivities: 1250,
      uniqueUsers: 450,
      eventTypeCounts: {
        login: 450,
        logout: 420,
        deposit: 120,
        withdrawal: 85,
        win: 280,
        game_play: 895,
      },
      lastHourMetrics: {
        timestamp: new Date(),
        logins: 58,
        deposits: 16,
        withdrawals: 7,
        wins: 35,
        gamePlays: 192,
      },
    };
  }),

  // Get top players
  getTopPlayers: protectedProcedure
    .input(z.object({ limit: z.number().default(10) }))
    .query(async ({ ctx, input }) => {
      if (ctx.user?.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return [
        {
          userId: 1001,
          activityCount: 156,
          lastActivity: new Date(),
        },
      ];
    }),
});

/**
 * Revenue Forecasting Router
 */
export const revenueForecastingRouter = router({
  // Get revenue forecast
  getForecast: protectedProcedure
    .input(
      z.object({
        modelType: z.enum(['ml', 'arima', 'exponential']).default('ml'),
        daysAhead: z.number().default(30),
      })
    )
    .query(async ({ ctx, input }) => {
      if (ctx.user?.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return await forecastingService.generateRevenueForecast(input.modelType, input.daysAhead);
    }),

  // Get revenue by source
  getRevenueBySource: protectedProcedure.query(async ({ ctx }) => {
    if (ctx.user?.role !== 'admin') {
      throw new Error('Unauthorized');
    }

    return await forecastingService.getRevenueBySource();
  }),

  // Get forecast insights
  getForecastInsights: protectedProcedure.query(async ({ ctx }) => {
    if (ctx.user?.role !== 'admin') {
      throw new Error('Unauthorized');
    }

    return await forecastingService.generateForecastInsights();
  }),

  // Get forecast accuracy
  getForecastAccuracy: protectedProcedure.query(async ({ ctx }) => {
    if (ctx.user?.role !== 'admin') {
      throw new Error('Unauthorized');
    }

    return await forecastingService.getForecastAccuracyMetrics();
  }),

  // Compare models
  compareModels: protectedProcedure.query(async ({ ctx }) => {
    if (ctx.user?.role !== 'admin') {
      throw new Error('Unauthorized');
    }

    return await forecastingService.compareModels();
  }),

  // Retrain model
  retrainModel: protectedProcedure
    .input(z.object({ modelType: z.enum(['ml', 'arima', 'exponential']) }))
    .mutation(async ({ ctx, input }) => {
      if (ctx.user?.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return await forecastingService.retrainForecastModel(input.modelType);
    }),
});

/**
 * Combined Advanced Features Router
 */
export const advancedFeaturesRouter = router({
  retentionCampaigns: retentionCampaignRouter,
  activityFeed: activityFeedRouter,
  revenueForecasting: revenueForecastingRouter,
});
