import { z } from "zod";
import { protectedProcedure, publicProcedure, router } from "../_core/trpc.ts";
import {
  getPoolSharkTables,
  getPoolSharkTableWithMatch,
  joinPoolSharkTable,
  completePoolSharkMatch,
  getPoolSharkLeaderboard,
  getUserPoolSharkStats,
} from "../poolShark.ts";
import { writeAuditLog } from "../db.ts";

export const poolSharkRouter = router({
  /**
   * Get all active Pool Shark tables
   */
  getTables: publicProcedure.query(async () => {
    return getPoolSharkTables();
  }),

  /**
   * Get a specific Pool Shark table with current match info
   */
  getTableWithMatch: publicProcedure
    .input(z.object({ tableId: z.number() }))
    .query(async ({ input }) => {
      return getPoolSharkTableWithMatch(input.tableId);
    }),

  /**
   * Join a Pool Shark table or add to waiting list
   */
  joinTable: protectedProcedure
    .input(z.object({ tableId: z.number() }))
    .mutation(async ({ ctx, input }) => {
      try {
        const result = await joinPoolSharkTable(ctx.user.id, input.tableId);

        await writeAuditLog({
          actorId: ctx.user.id,
          actorRole: "user",
          action: "pool_shark_join_table",
          category: "game",
          details: {
            tableId: input.tableId,
            status: result.status,
            matchId: result.matchId,
          },
        });

        return result;
      } catch (error: any) {
        throw new Error(error.message || "Failed to join Pool Shark table");
      }
    }),

  /**
   * Complete a Pool Shark match and award prizes
   */
  completeMatch: protectedProcedure
    .input(
      z.object({
        matchId: z.number(),
        winnerId: z.number(),
        winnerBreak: z.number().default(0),
      })
    )
    .mutation(async ({ ctx, input }) => {
      try {
        await completePoolSharkMatch(
          input.matchId,
          input.winnerId,
          input.winnerBreak
        );

        await writeAuditLog({
          actorId: ctx.user.id,
          actorRole: "user",
          action: "pool_shark_complete_match",
          category: "game",
          details: {
            matchId: input.matchId,
            winnerId: input.winnerId,
            winnerBreak: input.winnerBreak,
          },
        });

        return { success: true, matchId: input.matchId };
      } catch (error: any) {
        throw new Error(error.message || "Failed to complete Pool Shark match");
      }
    }),

  /**
   * Get Pool Shark leaderboard
   */
  getLeaderboard: publicProcedure
    .input(
      z.object({
        limit: z.number().max(500).default(100),
        offset: z.number().default(0),
      })
    )
    .query(async ({ input }) => {
      return getPoolSharkLeaderboard(input.limit, input.offset);
    }),

  /**
   * Get user's Pool Shark stats and achievements
   */
  getUserStats: protectedProcedure.query(async ({ ctx }) => {
    return getUserPoolSharkStats(ctx.user.id);
  }),

  /**
   * Get user's Pool Shark stats by ID (for public profiles)
   */
  getUserStatsById: publicProcedure
    .input(z.object({ userId: z.number() }))
    .query(async ({ input }) => {
      return getUserPoolSharkStats(input.userId);
    }),
});
