/**
 * User Profile tRPC Router
 * Handles user profile data, rewards, and account management
 */

import { z } from 'zod';
import { protectedProcedure, router } from '../_core/trpc.ts';
import {
  getUserProfile,
  updateUserProfile,
  getUserRewardHistory,
  getUserGameStats,
  getUserAchievements,
  getUserPreferences,
  updateUserPreferences,
} from '../userProfileService.ts';

export const userProfileRouter = router({
  /**
   * Get complete user profile
   */
  getProfile: protectedProcedure.query(async ({ ctx }) => {
    try {
      const profile = await getUserProfile(ctx.user.id.toString());
      return profile;
    } catch (error) {
      console.error('[userProfileRouter] Error fetching profile:', error);
      throw error;
    }
  }),

  /**
   * Update user profile
   */
  updateProfile: protectedProcedure
    .input(
      z.object({
        username: z.string().optional(),
        avatar: z.string().optional(),
        email: z.string().email().optional(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      try {
        const success = await updateUserProfile(ctx.user.id.toString(), input);
        return { success };
      } catch (error) {
        console.error('[userProfileRouter] Error updating profile:', error);
        throw error;
      }
    }),

  /**
   * Get user reward history
   */
  getRewardHistory: protectedProcedure
    .input(
      z.object({
        limit: z.number().default(50),
      })
    )
    .query(async ({ ctx, input }) => {
      try {
        const rewards = await getUserRewardHistory(ctx.user.id.toString(), input.limit);
        return rewards;
      } catch (error) {
        console.error('[userProfileRouter] Error fetching reward history:', error);
        throw error;
      }
    }),

  /**
   * Get user game statistics
   */
  getGameStats: protectedProcedure.query(async ({ ctx }) => {
    try {
      const stats = await getUserGameStats(ctx.user.id.toString());
      return stats;
    } catch (error) {
      console.error('[userProfileRouter] Error fetching game stats:', error);
      throw error;
    }
  }),

  /**
   * Get user achievements
   */
  getAchievements: protectedProcedure.query(async ({ ctx }) => {
    try {
      const achievements = await getUserAchievements(ctx.user.id.toString());
      return achievements;
    } catch (error) {
      console.error('[userProfileRouter] Error fetching achievements:', error);
      throw error;
    }
  }),

  /**
   * Get user preferences
   */
  getPreferences: protectedProcedure.query(async ({ ctx }) => {
    try {
      const preferences = await getUserPreferences(ctx.user.id.toString());
      return preferences;
    } catch (error) {
      console.error('[userProfileRouter] Error fetching preferences:', error);
      throw error;
    }
  }),

  /**
   * Update user preferences
   */
  updatePreferences: protectedProcedure
    .input(
      z.object({
        emailNotifications: z.boolean().optional(),
        pushNotifications: z.boolean().optional(),
        marketingEmails: z.boolean().optional(),
        twoFactorEnabled: z.boolean().optional(),
        theme: z.enum(['light', 'dark', 'auto']).optional(),
        language: z.string().optional(),
        timezone: z.string().optional(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      try {
        const success = await updateUserPreferences(ctx.user.id.toString(), input);
        return { success };
      } catch (error) {
        console.error('[userProfileRouter] Error updating preferences:', error);
        throw error;
      }
    }),

  /**
   * Get user statistics summary
   */
  getStatsSummary: protectedProcedure.query(async ({ ctx }) => {
    try {
      const profile = await getUserProfile(ctx.user.id.toString());
      if (!profile) return null;

      return {
        totalGamesPlayed: profile.stats.totalGamesPlayed,
        totalWinnings: profile.stats.totalWinnings,
        totalLosses: profile.stats.totalLosses,
        winRate: profile.stats.winRate,
        vipTier: profile.vipStatus.tier,
        vipName: profile.vipStatus.name,
        vipProgress: profile.vipStatus.progressToNext,
        monthlyBonus: profile.vipStatus.monthlyBonus,
      };
    } catch (error) {
      console.error('[userProfileRouter] Error fetching stats summary:', error);
      throw error;
    }
  }),

  /**
   * Get user wallet information
   */
  getWallet: protectedProcedure.query(async ({ ctx }) => {
    try {
      const profile = await getUserProfile(ctx.user.id.toString());
      if (!profile) return null;

      return profile.wallet;
    } catch (error) {
      console.error('[userProfileRouter] Error fetching wallet:', error);
      throw error;
    }
  }),

  /**
   * Get user VIP status
   */
  getVIPStatus: protectedProcedure.query(async ({ ctx }) => {
    try {
      const profile = await getUserProfile(ctx.user.id.toString());
      if (!profile) return null;

      return profile.vipStatus;
    } catch (error) {
      console.error('[userProfileRouter] Error fetching VIP status:', error);
      throw error;
    }
  }),
});
