import type { PrismaClient } from "@prisma/client";

const FAILED_ATTEMPT_WINDOW_MS = 15 * 60 * 1000;
const MAX_FAILED_ATTEMPTS = 5;
const LOCKOUT_DURATION_MS = 15 * 60 * 1000;

export function getRemainingLockoutSeconds(lockedUntil: Date, now = new Date()): number {
  return Math.max(0, Math.ceil((lockedUntil.getTime() - now.getTime()) / 1000));
}

export async function recordFailedLoginAttempt(prisma: PrismaClient, userId: bigint, now = new Date()) {
  const user = await prisma.user.findUnique({
    where: { id: userId },
    select: { failedLoginAttempts: true, firstFailedLoginAt: true },
  });
  if (!user) return { locked: false as const, remainingSeconds: 0 };

  const firstAt = user.firstFailedLoginAt;
  const inWindow = firstAt && now.getTime() - firstAt.getTime() <= FAILED_ATTEMPT_WINDOW_MS;
  const failedCount = inWindow ? user.failedLoginAttempts + 1 : 1;
  const nextFirstFailedAt = inWindow ? firstAt : now;
  const shouldLock = failedCount >= MAX_FAILED_ATTEMPTS;
  const lockedUntil = shouldLock ? new Date(now.getTime() + LOCKOUT_DURATION_MS) : null;

  await prisma.user.update({
    where: { id: userId },
    data: {
      failedLoginAttempts: failedCount,
      firstFailedLoginAt: nextFirstFailedAt,
      lockedUntil,
    },
  });

  return {
    locked: shouldLock,
    remainingSeconds: shouldLock && lockedUntil ? getRemainingLockoutSeconds(lockedUntil, now) : 0,
  };
}

export async function clearLoginFailures(prisma: PrismaClient, userId: bigint) {
  await prisma.user.update({
    where: { id: userId },
    data: {
      failedLoginAttempts: 0,
      firstFailedLoginAt: null,
      lockedUntil: null,
    },
  });
}

