import "server-only";
import { db } from "./db";

const WINDOW_MS = 15 * 60 * 1000;
const MAX_FAILS_PER_ACCOUNT = 5;
const MAX_FAILS_PER_IP = 20;

/** Returns minutes until retry, or 0 when the attempt may proceed. Backed by MySQL so it works across processes. */
export async function loginBlocked(email: string, ip: string) {
  const since = new Date(Date.now() - WINDOW_MS);
  const [acct, byIp] = await Promise.all([
    db.loginAttempt.count({ where: { key: `${email.toLowerCase()}|${ip}`, success: false, createdAt: { gte: since } } }),
    db.loginAttempt.count({ where: { key: { endsWith: `|${ip}` }, success: false, createdAt: { gte: since } } }),
  ]);
  return acct >= MAX_FAILS_PER_ACCOUNT || byIp >= MAX_FAILS_PER_IP ? 15 : 0;
}

export async function recordLogin(email: string, ip: string, success: boolean) {
  await db.loginAttempt.create({ data: { key: `${email.toLowerCase()}|${ip}`, success } });
  if (Math.random() < 0.02) await db.loginAttempt.deleteMany({ where: { createdAt: { lt: new Date(Date.now() - 24 * 3600_000) } } });
}
