import prisma from "../prismaClient";

export type LoginStatus = "SUCCESS" | "FAILURE";
export type FailureReason =
  | "MISSING_CREDENTIALS"
  | "INVALID_CREDENTIALS"
  | "WRONG_PASSWORD"
  | "ACCOUNT_LOCKED"
  | "NOT_ACTIVATED"
  | "NOT_ALLOWED"
  | "UNKNOWN"
  | null;

export async function upsertLoginActivity(
  userId: string,
  activity: string,
  status: LoginStatus,
  failureReason: FailureReason
) {
  try {
    // Deduplicate identical events in a short window to avoid accidental duplicates
    const since = new Date(Date.now() - 2000);
    const recent = await prisma.loginActivity.findFirst({
      where: {
        userId,
        activity,
        status,
        failureReason: failureReason ?? null,
        createdAt: { gte: since },
      },
      orderBy: { createdAt: "desc" },
    });
    if (recent) return;

    await prisma.loginActivity.create({
      data: { userId, activity, status, failureReason } as any,
    });
  } catch (e: any) {
    console.warn("loginActivity upsert failed", {
      userId,
      activity,
      status,
      failureReason,
      error: e?.message || String(e),
    });
  }
}
