import express from "express"; import { PrismaClient } from "@prisma/client"; import { requireAuth, requireAdmin } from "../middleware/auth.js"; const prisma = new PrismaClient(); const router = express.Router(); router.use(requireAuth, requireAdmin); router.get("/bets", async (req, res, next) => { try { const bets = await prisma.bet.findMany({ include: { user: true, match: true, market: true, selection: true }, orderBy: { createdAt: "desc" } }); res.json(bets); } catch (err) { next(err); } }); router.get("/matches", async (req, res, next) => { try { const matches = await prisma.match.findMany({ include: { markets: { include: { selections: true } } }, orderBy: { startTime: "asc" } }); res.json(matches); } catch (err) { next(err); } }); router.post("/matches", async (req, res, next) => { try { const match = await prisma.match.create({ data: req.body }); res.status(201).json(match); } catch (err) { next(err); } }); router.post("/matches/:matchId/markets", async (req, res, next) => { try { const market = await prisma.market.create({ data: { ...req.body, matchId: req.params.matchId } }); res.status(201).json(market); } catch (err) { next(err); } }); router.post("/matches/auto-seed", async (req, res, next) => { try { const sports = [ { name: "Cricket", leagues: ["IPL", "Big Bash League", "T20 World Cup"], teams: ["India", "Australia", "England", "Mumbai Indians", "Chennai Super Kings", "Perth Scorchers"] }, { name: "Football", leagues: ["Premier League", "La Liga", "Champions League"], teams: ["Man Utd", "Chelsea", "Liverpool", "Real Madrid", "Barcelona", "Bayern Munich"] }, { name: "Tennis", leagues: ["Wimbledon", "US Open", "French Open"], teams: ["Djokovic", "Alcaraz", "Nadal", "Medvedev", "Sinner", "Zverev"] }, { name: "Basketball", leagues: ["NBA", "EuroLeague"], teams: ["Lakers", "Warriors", "Celtics", "Heat", "Real Madrid Baloncesto", "FC Barcelona Bàsquet"] }, { name: "Baseball", leagues: ["MLB"], teams: ["Yankees", "Red Sox", "Dodgers", "Giants", "Cubs", "Cardinals"] }, { name: "Kabaddi", leagues: ["Pro Kabaddi League"], teams: ["U Mumba", "Patna Pirates", "Bengaluru Bulls", "Jaipur Pink Panthers", "Dabang Delhi", "Puneri Paltan"] } ]; const matchesCreated = []; for (const sport of sports) { // Create 2 matches per sport for (let i = 0; i < 2; i++) { const league = sport.leagues[Math.floor(Math.random() * sport.leagues.length)]; const homeTeam = sport.teams[Math.floor(Math.random() * sport.teams.length)]; let awayTeam = sport.teams[Math.floor(Math.random() * sport.teams.length)]; while (awayTeam === homeTeam) { awayTeam = sport.teams[Math.floor(Math.random() * sport.teams.length)]; } // Random time within next 24 hours const startTime = new Date(Date.now() + Math.random() * 24 * 60 * 60 * 1000); const match = await prisma.match.create({ data: { sport: sport.name, league, homeTeam, awayTeam, startTime, status: "UPCOMING" } }); // Create Market const market = await prisma.market.create({ data: { matchId: match.id, type: "MATCH_WINNER", name: "Match Winner", isActive: true } }); // Create Selections const homeOdds = (1.5 + Math.random() * 2.0).toFixed(2); const awayOdds = (1.5 + Math.random() * 2.0).toFixed(2); const drawOdds = (2.5 + Math.random() * 2.0).toFixed(2); await prisma.marketSelection.create({ data: { matchId: match.id, marketId: market.id, label: homeTeam, side: "home", odds: parseFloat(homeOdds), isActive: true } }); await prisma.marketSelection.create({ data: { matchId: match.id, marketId: market.id, label: awayTeam, side: "away", odds: parseFloat(awayOdds), isActive: true } }); if (sport.name === "Football") { await prisma.marketSelection.create({ data: { matchId: match.id, marketId: market.id, label: "Draw", side: "draw", odds: parseFloat(drawOdds), isActive: true } }); } matchesCreated.push(match); } } res.status(201).json({ message: "Auto-seeded successfully", count: matchesCreated.length, matches: matchesCreated }); } catch (err) { next(err); } }); router.post("/markets/:marketId/selections", async (req, res, next) => { try { const selection = await prisma.marketSelection.create({ data: { ...req.body, marketId: req.params.marketId } }); res.status(201).json(selection); } catch (err) { next(err); } }); router.post("/bets/:betId/settle", async (req, res, next) => { try { const { result } = req.body; const bet = await prisma.bet.findUnique({ where: { id: req.params.betId } }); if (!bet) { return res.status(404).json({ message: "Bet not found" }); } if (bet.status !== "PENDING") { return res.status(400).json({ message: "Bet already settled" }); } const isWin = result === "WIN"; const updated = await prisma.$transaction(async (tx) => { const updatedBet = await tx.bet.update({ where: { id: bet.id }, data: { status: isWin ? "WON" : "LOST", settledAt: new Date() } }); if (isWin) { const wallet = await tx.wallet.update({ where: { userId: bet.userId }, data: { balance: { increment: bet.potentialPayout } } }); await tx.transaction.create({ data: { userId: bet.userId, walletId: wallet.id, type: "BET_SETTLED", amount: bet.potentialPayout, reference: `BET_WIN_${bet.id}` } }); } return updatedBet; }); res.json(updated); } catch (err) { next(err); } }); // Deposit Management router.get("/deposits", async (req, res, next) => { try { const deposits = await prisma.transaction.findMany({ where: { type: "DEPOSIT", status: "PENDING" }, include: { user: true }, orderBy: { createdAt: "asc" } }); res.json(deposits); } catch (err) { next(err); } }); router.post("/deposits/:txId/approve", async (req, res, next) => { try { const { txId } = req.params; const tx = await prisma.transaction.findUnique({ where: { id: txId } }); if (!tx) return res.status(404).json({ message: "Transaction not found" }); if (tx.status !== "PENDING") return res.status(400).json({ message: "Not pending" }); // Execute Approval const result = await prisma.$transaction(async (prismaTx) => { // 1. Update Transaction Status const updatedTx = await prismaTx.transaction.update({ where: { id: txId }, data: { status: "COMPLETED", // approvalTimestamp: new Date() // if we added this field, for now we just rely on updatedAt if it existed or just status change } }); // 2. Credit Wallet await prismaTx.wallet.update({ where: { userId: tx.userId }, data: { balance: { increment: tx.amount } } }); return updatedTx; }); res.json(result); } catch (err) { next(err); } }); router.post("/deposits/:txId/reject", async (req, res, next) => { try { const { txId } = req.params; const tx = await prisma.transaction.findUnique({ where: { id: txId } }); if (!tx) return res.status(404).json({ message: "Transaction not found" }); if (tx.status !== "PENDING") return res.status(400).json({ message: "Not pending" }); const updatedTx = await prisma.transaction.update({ where: { id: txId }, data: { status: "REJECTED" } }); res.json(updatedTx); } catch (err) { next(err); } }); export default router;