import "server-only";

import { db } from "../db";

const WINDOW_MINUTES = 15;
const MAX_FAILURES_PER_USERNAME = 5;
const MAX_FAILURES_PER_IP = 20;
const RETENTION_DAYS = 30;

export const RATE_LIMIT_WINDOW_MINUTES = WINDOW_MINUTES;

export async function isLoginBlocked(username: string, ip: string): Promise<boolean> {
  const since = new Date(Date.now() - WINDOW_MINUTES * 60 * 1000);

  const [byUsername, byIp] = await Promise.all([
    db.loginAttempt.count({
      where: { username, success: false, createdAt: { gte: since } },
    }),
    db.loginAttempt.count({
      where: { ip, success: false, createdAt: { gte: since } },
    }),
  ]);

  return byUsername >= MAX_FAILURES_PER_USERNAME || byIp >= MAX_FAILURES_PER_IP;
}

export async function recordLoginAttempt(username: string, ip: string, success: boolean) {
  await db.loginAttempt.create({ data: { username, ip, success } });

  if (success) {
    // A successful login clears that user's failure streak.
    await db.loginAttempt.deleteMany({ where: { username, success: false } });
  }
}

export async function purgeOldLoginAttempts(): Promise<void> {
  const before = new Date(Date.now() - RETENTION_DAYS * 24 * 60 * 60 * 1000);
  await db.loginAttempt.deleteMany({ where: { createdAt: { lt: before } } });
}
