import { prisma } from './db';
const A = 'ABCDEFGHJKLMNPRSTUVYZ23456789';
/** Kullanıcının davet kodu (eski hesaplarda ilk ihtiyaçta üretilir). */
export async function ensureRefCode(u: { id: string; refCode: string | null }) {
  if (u.refCode) return u.refCode;
  for (let i = 0; i < 5; i++) {
    const code = Array.from(crypto.getRandomValues(new Uint8Array(6)), (b) => A[b % A.length]).join('');
    try { await prisma.user.update({ where: { id: u.id }, data: { refCode: code } }); return code; } catch { /* çakışma: tekrar */ }
  }
  throw new Error('davet kodu üretilemedi');
}
export async function refStats(userId: string) {
  const [joined, rewarded] = await Promise.all([
    prisma.user.count({ where: { referredById: userId } }),
    prisma.user.count({ where: { referredById: userId, refRewardedAt: { not: null } } }),
  ]);
  return { joined, rewarded };
}
