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

/** Brute-force lockout backed by the LoginAttempt table. Only failed attempts are recorded — call clearAttempts on success. */
export async function isRateLimited(identifier: string, windowMs: number, maxAttempts: number): Promise<boolean> {
  const since = new Date(Date.now() - windowMs);
  const count = await prisma.loginAttempt.count({ where: { identifier, createdAt: { gte: since } } });
  return count >= maxAttempts;
}

export async function recordFailedAttempt(identifier: string): Promise<void> {
  await prisma.loginAttempt.create({ data: { identifier } });
  // Opportunistic cleanup so the table doesn't grow unbounded — anything older than a day is long past any lockout window.
  const dayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
  await prisma.loginAttempt.deleteMany({ where: { identifier, createdAt: { lt: dayAgo } } });
}

export async function clearAttempts(identifier: string): Promise<void> {
  await prisma.loginAttempt.deleteMany({ where: { identifier } });
}
