import { router, publicProcedure, protectedProcedure } from "../_core/trpc.ts";
import { z } from "zod";
import {
  getPlayerVIPStatus,
  updatePlayerSpend,
  addCashback,
  claimMonthlyBonus,
  claimBirthdayBonus,
  getVIPTierInfo,
  getAllVIPTiers,
  getExclusiveGames,
  getVIPStats,
} from "../services/vipPerksService.ts";

export const vipPerksRouter = router({
  // Get player's VIP status
  getStatus: protectedProcedure.query(async ({ ctx }) => {
    if (!ctx.user) throw new Error("User not authenticated");
    return await getPlayerVIPStatus(ctx.user.id);
  }),

  // Update player spend (internal use)
  updateSpend: protectedProcedure
    .input(z.object({ amount: z.number() }))
    .mutation(async ({ input, ctx }) => {
      if (!ctx.user) throw new Error("User not authenticated");
      const newTier = await updatePlayerSpend(ctx.user.id, input.amount);
      return { success: true, newTier };
    }),

  // Add cashback (internal use)
  addCashback: protectedProcedure
    .input(z.object({ amount: z.number() }))
    .mutation(async ({ input, ctx }) => {
      if (!ctx.user) throw new Error("User not authenticated");
      const cashback = await addCashback(ctx.user.id, input.amount);
      return { success: true, cashback };
    }),

  // Claim monthly bonus
  claimMonthlyBonus: protectedProcedure.mutation(async ({ ctx }) => {
    if (!ctx.user) throw new Error("User not authenticated");
    const bonus = await claimMonthlyBonus(ctx.user.id);
    return { success: true, bonus };
  }),

  // Claim birthday bonus
  claimBirthdayBonus: protectedProcedure.mutation(async ({ ctx }) => {
    if (!ctx.user) throw new Error("User not authenticated");
    const bonus = await claimBirthdayBonus(ctx.user.id);
    return { success: true, bonus };
  }),

  // Get VIP tier info
  getTierInfo: publicProcedure
    .input(z.object({ tier: z.enum(["bronze", "silver", "gold", "platinum", "diamond", "elite"]) }))
    .query(async ({ input }) => {
      return await getVIPTierInfo(input.tier);
    }),

  // Get all VIP tiers
  getAllTiers: publicProcedure.query(async () => {
    return await getAllVIPTiers();
  }),

  // Get exclusive games for player
  getExclusiveGames: protectedProcedure.query(async ({ ctx }) => {
    if (!ctx.user) throw new Error("User not authenticated");
    return await getExclusiveGames(ctx.user.id);
  }),

  // Get VIP statistics
  getStats: publicProcedure.query(async () => {
    return await getVIPStats();
  }),
});
