import { router, adminProcedure } from "../_core/trpc.ts";
import { z } from "zod";
import { casinoGames } from "../../drizzle/schema.ts";
import { getDb } from "../db.ts";
import fs from "fs";

export const gamesImportRouter = router({
  importSlotGames: adminProcedure
    .input(z.object({
      filePath: z.string().optional(),
      limit: z.number().optional().default(6015),
    }))
    .mutation(async ({ input }) => {
      const db = await getDb();
      try {
        // Read games from the import file
        const filePath = input.filePath || "/home/ubuntu/coinkrazy/games-import.json";
        
        if (!fs.existsSync(filePath)) {
          throw new Error(`Games import file not found at ${filePath}`);
        }

        const gamesData = JSON.parse(fs.readFileSync(filePath, "utf-8"));
        const gamesToImport = gamesData.slice(0, input.limit);

        console.log(`[Games Import] Starting import of ${gamesToImport.length} games...`);

        // Transform games to match casinoGames schema
        const transformedGames = gamesToImport.map((game: any) => ({
          slug: game.gameId.toLowerCase().replace(/\//g, "-"),
          title: game.gameName,
          provider: game.provider,
          category: "slots",
          tags: [game.gameType, game.volatility],
          thumbnailUrl: game.iconUrl,
          bannerUrl: game.iconUrl,
          rtp: game.rtp * 100, // Convert to percentage
          volatility: game.volatility || "medium",
          minBetGc: 1.0,
          maxBetGc: 1000.0,
          minBetSc: 0.01,
          maxBetSc: 100.0,
          isActive: game.isActive ? 1 : 0,
          isFeatured: game.isFeatured ? 1 : 0,
          isNew: 0,
          playCount: 0,
          description: game.description,
          features: {
            paylines: game.paylines,
            reels: game.reels,
            gameType: game.gameType,
          },
          paylines: game.paylines,
          reels: game.reels,
        }));

        // Batch insert games (insert in chunks of 100 to avoid timeout)
        let importedCount = 0;
        const chunkSize = 100;

        for (let i = 0; i < transformedGames.length; i += chunkSize) {
          const chunk = transformedGames.slice(i, i + chunkSize);
          
          try {
            // Use raw SQL for bulk insert to avoid Drizzle issues
            const values = chunk.map(g => [
              g.slug,
              g.title,
              g.provider,
              g.category,
              JSON.stringify(g.tags),
              g.thumbnailUrl,
              g.bannerUrl,
              g.rtp,
              g.volatility,
              g.minBetGc,
              g.maxBetGc,
              g.minBetSc,
              g.maxBetSc,
              g.isActive,
              g.isFeatured,
              g.isNew,
              g.playCount,
              g.description,
              JSON.stringify(g.features),
              g.paylines,
              g.reels,
            ]);

            // Insert chunk
            await db.insert(casinoGames).values(chunk as any);
            importedCount += chunk.length;
            
            console.log(`[Games Import] Imported ${importedCount}/${transformedGames.length} games...`);
          } catch (error) {
            console.error(`[Games Import] Error importing chunk ${i}-${i + chunkSize}:`, error);
            // Continue with next chunk even if this one fails
          }
        }

        console.log(`[Games Import] ✅ Successfully imported ${importedCount} games`);

        return {
          success: true,
          importedCount,
          totalGames: transformedGames.length,
        };
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        console.error("[Games Import] Error:", errorMessage);
        throw new Error(`Games import failed: ${errorMessage}`);
      }
    }),

  getGameStats: adminProcedure.query(async () => {
    const db = await getDb();
    try {
      const stats = await db.query.casinoGames.findMany({
        columns: {
          provider: true,
        },
      });

      // Count games by provider
      const providerCounts: Record<string, number> = {};
      stats.forEach(game => {
        providerCounts[game.provider] = (providerCounts[game.provider] || 0) + 1;
      });

      return {
        totalGames: stats.length,
        uniqueProviders: Object.keys(providerCounts).length,
        providerCounts,
      };
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      throw new Error(`Failed to get game stats: ${errorMessage}`);
    }
  }),

  listGames: adminProcedure
    .input(z.object({
      provider: z.string().optional(),
      limit: z.number().default(50),
      offset: z.number().default(0),
    }))
    .query(async ({ input }) => {
      const db = await getDb();
      try {
        let query = db.query.casinoGames.findMany({
          limit: input.limit,
          offset: input.offset,
        });

        if (input.provider) {
          query = db.query.casinoGames.findMany({
            where: (games, { eq }) => eq(games.provider, input.provider),
            limit: input.limit,
            offset: input.offset,
          });
        }

        return await query;
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        throw new Error(`Failed to list games: ${errorMessage}`);
      }
    }),
});
