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

const analyticsService = new UserPreferenceAnalyticsService();

export const userPreferenceAnalyticsRouter = router({
  /**
   * Set user preference
   */
  setPreference: protectedProcedure
    .input(
      z.object({
        notificationType: z.enum(['promotion', 'announcement', 'event', 'reward', 'engagement', 'system']),
        channel: z.enum(['push', 'email', 'in_app']),
        enabled: z.boolean(),
        frequency: z.enum(['instant', 'daily', 'weekly', 'never']).optional(),
      })
    )
    .mutation(({ input, ctx }) => {
      return analyticsService.setUserPreference(
        ctx.user.id,
        input.notificationType,
        input.channel,
        input.enabled,
        input.frequency || 'instant'
      );
    }),

  /**
   * Get user preferences
   */
  getUserPreferences: protectedProcedure.query(({ ctx }) => {
    return analyticsService.getUserPreferences(ctx.user.id);
  }),

  /**
   * Track user engagement
   */
  trackEngagement: protectedProcedure
    .input(
      z.object({
        notificationType: z.enum(['promotion', 'announcement', 'event', 'reward', 'engagement', 'system']),
        channel: z.enum(['push', 'email', 'in_app']),
        eventType: z.enum(['received', 'opened', 'clicked']),
        hour: z.number().min(0).max(23),
      })
    )
    .mutation(({ input, ctx }) => {
      analyticsService.trackUserEngagement(
        ctx.user.id,
        input.notificationType,
        input.channel,
        input.eventType,
        input.hour
      );
      return { success: true };
    }),

  /**
   * Get user engagement metrics
   */
  getUserEngagementMetrics: protectedProcedure.query(({ ctx }) => {
    return analyticsService.getUserEngagementMetrics(ctx.user.id);
  }),

  /**
   * Get optimal send time
   */
  getOptimalSendTime: protectedProcedure.query(({ ctx }) => {
    return analyticsService.getOptimalSendTime(ctx.user.id);
  }),

  /**
   * Get notification type preferences
   */
  getNotificationTypePreferences: protectedProcedure.query(({ ctx }) => {
    return analyticsService.getNotificationTypePreferences(ctx.user.id);
  }),

  /**
   * Get channel preferences
   */
  getChannelPreferences: protectedProcedure.query(({ ctx }) => {
    return analyticsService.getChannelPreferences(ctx.user.id);
  }),

  /**
   * Get recommendation
   */
  getRecommendation: protectedProcedure.query(({ ctx }) => {
    return analyticsService.getRecommendation(ctx.user.id);
  }),

  /**
   * Analyze segment preferences (admin only)
   */
  analyzeSegmentPreferences: protectedProcedure
    .input(z.object({ userIds: z.array(z.string()), segment: z.string() }))
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return analyticsService.analyzeSegmentPreferences(input.userIds, input.segment);
    }),

  /**
   * Get segment preferences (admin only)
   */
  getSegmentPreferences: protectedProcedure
    .input(z.object({ segment: z.string() }))
    .query(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return analyticsService.getSegmentPreferences(input.segment);
    }),

  /**
   * Get all segment preferences (admin only)
   */
  getAllSegmentPreferences: protectedProcedure.query(({ ctx }) => {
    // Check if user is admin
    if (ctx.user.role !== 'admin') {
      throw new Error('Unauthorized');
    }

    return analyticsService.getAllSegmentPreferences();
  }),

  /**
   * Get user segments by preference (admin only)
   */
  getUserSegmentsByPreference: protectedProcedure
    .input(
      z.object({
        notificationType: z.enum(['promotion', 'announcement', 'event', 'reward', 'engagement', 'system']),
        channel: z.enum(['push', 'email', 'in_app']),
      })
    )
    .query(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return analyticsService.getUserSegmentsByPreference(input.notificationType, input.channel);
    }),

  /**
   * Get analytics summary (admin only)
   */
  getAnalyticsSummary: protectedProcedure.query(({ ctx }) => {
    // Check if user is admin
    if (ctx.user.role !== 'admin') {
      throw new Error('Unauthorized');
    }

    return analyticsService.getAnalyticsSummary();
  }),
});

export default userPreferenceAnalyticsRouter;
