import { prisma } from '@/lib/prisma';

const PRUNE_AGE_MS = 24 * 60 * 60 * 1000; // 24h

// Reads the first hop of x-forwarded-for, which is what the reverse proxy in
// front of most hosts (Vercel included) sets to the real client IP. Falls
// back to a shared bucket if it's ever missing (e.g. local dev without a
// proxy) rather than throwing — worse rate limiting beats a crashed request.
export function getClientIp(headersList: Headers) {
  const forwarded = headersList.get('x-forwarded-for');
  if (forwarded) return forwarded.split(',')[0].trim();
  return 'unknown';
}

// DB-backed rather than in-memory: an in-memory counter resets on every
// serverless cold start and doesn't share state across instances, so it
// would silently stop working outside a single always-on server.
export async function checkRateLimit(key: string, limit: number, windowMs: number) {
  const windowStart = new Date(Date.now() - windowMs);

  const count = await prisma.rateLimitAttempt.count({
    where: { key, createdAt: { gte: windowStart } },
  });

  if (count >= limit) {
    return { allowed: false as const };
  }

  await prisma.rateLimitAttempt.create({ data: { key } });

  // Opportunistic cleanup so the table doesn't grow unbounded — cheap at
  // this scale, no separate cron needed.
  await prisma.rateLimitAttempt.deleteMany({
    where: { createdAt: { lt: new Date(Date.now() - PRUNE_AGE_MS) } },
  });

  return { allowed: true as const };
}
