import 'server-only' import { prisma } from './db' import { getArmyFeed } from './lokilab-feed' export async function followPick(userId: string, lotteryId: string, country: string, targetDrawDate: string) { await prisma.followedPick.upsert({ where: { userId_lotteryId_targetDrawDate: { userId, lotteryId, targetDrawDate } }, update: {}, create: { userId, lotteryId, country, targetDrawDate }, }) } export async function unfollowPick(userId: string, lotteryId: string, targetDrawDate: string) { await prisma.followedPick.deleteMany({ where: { userId, lotteryId, targetDrawDate } }) } export async function listFollowedPicks(userId: string) { return prisma.followedPick.findMany({ where: { userId }, orderBy: { createdAt: 'desc' } }) } export interface MemberStanding { userId: string displayName: string avatarUrl: string | null followed: number wins: number winRate: number } /** * Leaderboard = who follows Loki's picks most accurately, not who won money. * Resolution reuses LokiLab's own lastDraw.won per lottery/date rather than * re-deriving win logic here — a follow only counts once the matching * lottery/date pair shows up as LokiLab's most recent resolved draw. */ export async function leaderboard(limit = 20): Promise { const feed = await getArmyFeed() const resolvedByKey = new Map() for (const l of feed.lotteries) { if (l.lastDraw?.pick) resolvedByKey.set(`${l.id}:${l.lastDraw.date}`, l.lastDraw.won ?? false) } const follows = await prisma.followedPick.findMany({ include: { user: { select: { id: true, name: true, publicNickname: true, avatarUrl: true } } }, }) const byUser = new Map() for (const f of follows) { const key = `${f.lotteryId}:${f.targetDrawDate}` if (!resolvedByKey.has(key)) continue const won = resolvedByKey.get(key)! const entry = byUser.get(f.userId) ?? ({ userId: f.userId, displayName: f.user.publicNickname || f.user.name, avatarUrl: f.user.avatarUrl, followed: 0, wins: 0, winRate: 0, } satisfies MemberStanding) entry.followed++ if (won) entry.wins++ byUser.set(f.userId, entry) } const standings = [...byUser.values()].map((s) => ({ ...s, winRate: s.followed > 0 ? s.wins / s.followed : 0 })) standings.sort((a, b) => b.winRate - a.winRate || b.followed - a.followed) return standings.slice(0, limit) }