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

/**
 * Badge System Router
 * Manages player badges, achievements, and progression
 */
export const badgeSystemRouter = router({
  /**
   * Get all available badges
   */
  getAllBadges: protectedProcedure.query(async () => {
    return [
      {
        badgeId: 'badge_001',
        name: 'First Win',
        description: 'Win your first game',
        icon: 'trophy',
        category: 'achievement',
        rarity: 'common',
        unlocked: true,
        unlockedDate: new Date('2024-01-15'),
      },
      {
        badgeId: 'badge_002',
        name: 'High Roller',
        description: 'Wager $1,000 in a single session',
        icon: 'diamond',
        category: 'achievement',
        rarity: 'rare',
        unlocked: true,
        unlockedDate: new Date('2024-02-20'),
      },
      {
        badgeId: 'badge_003',
        name: 'Tournament Champion',
        description: 'Win a tournament',
        icon: 'crown',
        category: 'tournament',
        rarity: 'epic',
        unlocked: false,
        unlockedDate: null,
      },
      {
        badgeId: 'badge_004',
        name: 'Social Butterfly',
        description: 'Refer 5 friends',
        icon: 'share',
        category: 'engagement',
        rarity: 'uncommon',
        unlocked: true,
        unlockedDate: new Date('2024-03-10'),
      },
      {
        badgeId: 'badge_005',
        name: 'Legendary Player',
        description: 'Reach level 50',
        icon: 'star',
        category: 'progression',
        rarity: 'legendary',
        unlocked: false,
        unlockedDate: null,
      },
    ];
  }),

  /**
   * Get player's badges
   */
  getPlayerBadges: protectedProcedure.query(async ({ ctx }) => {
    // In production, query from database
    return [
      {
        badgeId: 'badge_001',
        name: 'First Win',
        unlockedDate: new Date('2024-01-15'),
        progress: 100,
      },
      {
        badgeId: 'badge_002',
        name: 'High Roller',
        unlockedDate: new Date('2024-02-20'),
        progress: 100,
      },
      {
        badgeId: 'badge_004',
        name: 'Social Butterfly',
        unlockedDate: new Date('2024-03-10'),
        progress: 100,
      },
    ];
  }),

  /**
   * Get badge progress for a specific badge
   */
  getBadgeProgress: protectedProcedure
    .input(z.object({ badgeId: z.string() }))
    .query(async ({ ctx, input }) => {
      // In production, calculate from player data
      const progressMap: Record<string, number> = {
        badge_001: 100,
        badge_002: 100,
        badge_003: 0,
        badge_004: 100,
        badge_005: 42, // Level 21 out of 50
      };

      return {
        badgeId: input.badgeId,
        progress: progressMap[input.badgeId] || 0,
        nextMilestone: 'Level 25',
      };
    }),

  /**
   * Get nearby badges (badges player is close to unlocking)
   */
  getNearbyBadges: protectedProcedure
    .input(z.object({ limit: z.number().default(5) }))
    .query(async ({ ctx, input }) => {
      return [
        {
          badgeId: 'badge_005',
          name: 'Legendary Player',
          description: 'Reach level 50',
          progress: 42,
          progressPercentage: 84,
          nextMilestone: 'Level 25 (8 more levels)',
        },
        {
          badgeId: 'badge_006',
          name: 'Crypto Pioneer',
          description: 'Complete 10 crypto deposits',
          progress: 7,
          progressPercentage: 70,
          nextMilestone: '3 more deposits needed',
        },
        {
          badgeId: 'badge_007',
          name: 'Tournament Master',
          description: 'Win 5 tournaments',
          progress: 2,
          progressPercentage: 40,
          nextMilestone: '3 more tournament wins',
        },
      ].slice(0, input.limit);
    }),

  /**
   * Get badge statistics
   */
  getBadgeStatistics: protectedProcedure.query(async ({ ctx }) => {
    return {
      totalBadges: 25,
      unlockedBadges: 8,
      unlockedPercentage: 32,
      recentlyUnlocked: [
        { badgeId: 'badge_004', name: 'Social Butterfly', unlockedDate: new Date('2024-03-10') },
        { badgeId: 'badge_002', name: 'High Roller', unlockedDate: new Date('2024-02-20') },
      ],
      badgesByCategory: {
        achievement: 8,
        tournament: 5,
        engagement: 7,
        progression: 5,
      },
    };
  }),

  /**
   * Unlock a badge (admin/system use)
   */
  unlockBadge: protectedProcedure
    .input(
      z.object({
        badgeId: z.string(),
        userId: z.string().optional(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      const userId = input.userId || ctx.user.id;
      // In production, save to database and trigger notification
      return {
        success: true,
        badgeId: input.badgeId,
        unlockedDate: new Date(),
        message: 'Badge unlocked! Check your profile.',
      };
    }),

  /**
   * Create custom badge (admin)
   */
  createBadge: adminProcedure
    .input(
      z.object({
        name: z.string(),
        description: z.string(),
        icon: z.string(),
        category: z.enum(['achievement', 'tournament', 'engagement', 'progression', 'special']),
        rarity: z.enum(['common', 'uncommon', 'rare', 'epic', 'legendary']),
        unlockCriteria: z.string(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      // In production, save to database
      return {
        success: true,
        badgeId: `badge_${Date.now()}`,
        ...input,
      };
    }),

  /**
   * Get badge leaderboard
   */
  getBadgeLeaderboard: protectedProcedure
    .input(
      z.object({
        badgeId: z.string(),
        limit: z.number().default(10),
      })
    )
    .query(async ({ ctx, input }) => {
      return [
        { rank: 1, playerName: 'ProPlayer123', unlockedDate: new Date('2024-01-10'), level: 50 },
        { rank: 2, playerName: 'CasinoKing', unlockedDate: new Date('2024-01-15'), level: 48 },
        { rank: 3, playerName: 'LuckyStrike', unlockedDate: new Date('2024-01-20'), level: 47 },
      ].slice(0, input.limit);
    }),

  /**
   * Get badge collection showcase
   */
  getBadgeShowcase: protectedProcedure
    .input(z.object({ userId: z.string().optional() }))
    .query(async ({ ctx, input }) => {
      const userId = input.userId || ctx.user.id;
      return {
        userId,
        totalBadges: 8,
        displayedBadges: [
          { badgeId: 'badge_001', name: 'First Win', icon: 'trophy' },
          { badgeId: 'badge_002', name: 'High Roller', icon: 'diamond' },
          { badgeId: 'badge_004', name: 'Social Butterfly', icon: 'share' },
        ],
        profileBadge: 'badge_002', // Primary badge displayed on profile
      };
    }),

  /**
   * Update badge showcase (reorder/select badges)
   */
  updateBadgeShowcase: protectedProcedure
    .input(
      z.object({
        displayedBadges: z.array(z.string()),
        profileBadge: z.string(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      // In production, save to database
      return {
        success: true,
        message: 'Badge showcase updated',
      };
    }),

  /**
   * Get badge rewards
   */
  getBadgeRewards: protectedProcedure.query(async () => {
    return [
      {
        badgeId: 'badge_001',
        rewards: {
          scBonus: 10,
          freeSpins: 5,
          multiplier: 1.0,
        },
      },
      {
        badgeId: 'badge_002',
        rewards: {
          scBonus: 50,
          freeSpins: 25,
          multiplier: 1.1,
        },
      },
      {
        badgeId: 'badge_005',
        rewards: {
          scBonus: 500,
          freeSpins: 100,
          multiplier: 1.5,
        },
      },
    ];
  }),

  /**
   * Get badge progression path
   */
  getBadgeProgressionPath: protectedProcedure.query(async () => {
    return {
      currentLevel: 21,
      nextLevel: 22,
      progressToNextLevel: 65,
      badges: [
        { level: 5, badge: 'badge_001', name: 'First Win' },
        { level: 10, badge: 'badge_002', name: 'High Roller' },
        { level: 15, badge: 'badge_004', name: 'Social Butterfly' },
        { level: 25, badge: 'badge_005', name: 'Legendary Player' },
        { level: 50, badge: 'badge_006', name: 'Master of All' },
      ],
    };
  }),

  /**
   * Get badge analytics (admin)
   */
  getBadgeAnalytics: adminProcedure.query(async () => {
    return {
      totalBadges: 25,
      totalUnlocks: 45230,
      avgBadgesPerPlayer: 3.2,
      mostCommonBadges: [
        { badgeId: 'badge_001', name: 'First Win', unlocks: 8500 },
        { badgeId: 'badge_002', name: 'High Roller', unlocks: 4200 },
        { badgeId: 'badge_004', name: 'Social Butterfly', unlocks: 3100 },
      ],
      rarelyUnlockedBadges: [
        { badgeId: 'badge_005', name: 'Legendary Player', unlocks: 45 },
        { badgeId: 'badge_006', name: 'Master of All', unlocks: 12 },
      ],
    };
  }),
});
